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.