Medium
LABMinimum Number of Swaps to Make the String Balanced
Given a bracket string with equal [ and ], return the minimum swaps needed to make it balanced.
EXAMPLES
Example 1
Input
{
"s": "][]["
}
Output
1FUNCTION SHAPE
s: string→intSOLUTION NOTE
After removing matched pairs, we have "]]][[[" pattern. Each swap fixes 2 brackets, so ceil(unmatched/2).
Reveal reference solution +
pythonREFERENCE
def minSwaps(self, s: str) -> int:
unmatched = 0
for c in s:
if c == '[':
unmatched += 1
elif unmatched > 0:
unmatched -= 1
return (unmatched + 1) // 2Time
O(n)Space
O(1)