![]() |
VOOZH | about |
Given a string s of length 2n containing exactly n '[' and n ']' brackets. Find the minimum number of adjacent swaps needed to make the string balanced.
Note: A string is balanced if every '[' has a matching ']' such that no closing bracket appears before its corresponding opening bracket, and the total counts of both are equal.
Examples:
Input : s = "[]][]["
Output : 2
Explanation : First swap Position 3 and 4 "[][]][" and Second swapPosition 5 and 6 "[][][]"Input : s = "[[][]]"
Output : 0
Explanation : The string is already balanced.
Table of Content
We traverse the string while keeping track of the balance between '[' and ']'. Whenever the balance becomes negative, it indicates an excess of ']'. To fix this, we locate the next '[' ahead in the string and swap it leftward to the current position. Each such swap adds the distance between these indices to the total count. After adjusting, the balance is reset, and the traversal continues. The accumulated swap count at the end gives the minimum number of swaps needed to balance the string.
2
We first store the positions of all '[' in a vector. While scanning the string, we keep a balance counter that goes up for '[' and down for ']'. If the balance becomes negative, it means there are too many ']'. To fix it, we take the next '[' from our vector, swap it forward, and add the swap distance to the answer.
2
We traverse the string from left to right while keeping track of how many [ and ] we have seen. Whenever the number of ] becomes greater than [, we say there is an imbalance. Later, when we encounter a [, if imbalance > 0, it means this [ must be shifted left to balance one of the earlier unmatched ]. The number of swaps needed is exactly equal to the current imbalance, so we add it to our total swap count and decrease the imbalance by 1. By the end of the scan, the accumulated count gives the minimum adjacent swaps required.
2