Minimum moves required to make string of bracket balanced
Minimum moves required to make string of bracket balanced given a imbalanced brackets. This is question recently asked me in the interview, So I wanted to share it.
PYTHON PROGRAM
Luminari
7/14/20241 min read
Question:
Calculate the minimum number of swaps necessary to make a string balanced
Logic:
Initialize sum = 0 to store the result.
Maintain a count of the number of '[' brackets encountered.
Reduce this count when encountering a ']' character.
If the count becomes negative, we must start balancing the string.
Let index i represent the current position.
Move forward to the next '[' at index j.
Increase sum by j - i.
Swap the '[' at position j with the one at position i, shifting other characters to the right.
Set the count back to 1 and continue traversing the string.
Solution in python:
# Example usage s1 = "[]][][" s2 = "[[][]]"
print(swapCount(s1)) # Output: 2
print(swapCount(s2)) # Output: 0
There are lot of sources are there when it comes to learning python. I will share if something is worth of sharing.. Stay tuned
Preparing for interview?
Checkout our Interview prep page, It might help you.
My interests
As a techie + proud Hindhu i love to know/write about technology, spiritual knowledge.
Hey!, I am not living library. But if there is topic if you want me to cover, I will do my research and write about it, if it is unfamiliar to me. Its fun to learn and grow together.
Contact ID
Contact
author@luminari.info
© 2024. All rights reserved.