#1963
Minimum Number of Swaps to Make the String Balanced
MediumTwo PointersStringStackGreedyGreedyTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n!) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses a greedy approach to count the number of misplaced closing brackets as we traverse the string. This allows us to calculate the minimum swaps needed without generating permutations.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a variable to track the balance of brackets.
- 2Step 2: Traverse the string and update the balance for each character: +1 for '[' and -1 for ']'.
- 3Step 3: Whenever the balance goes negative, it indicates a misplaced closing bracket, so increment the swap count.
- 4Step 4: The number of swaps needed is equal to the number of times the balance went negative divided by 2.
solution.py15 lines
1# Full working Python code
2
3def min_swaps_optimal(s):
4 balance = 0
5 swaps = 0
6 for char in s:
7 if char == '[':
8 balance += 1
9 else:
10 balance -= 1
11 if balance < 0:
12 swaps += 1
13 balance = 0 # Reset balance after counting a swap
14 return swaps
15ℹ
Complexity note: The time complexity is O(n) because we only traverse the string once, and the space complexity is O(1) since we only use a few variables for counting.
- 1The balance of brackets can be tracked to determine how many swaps are needed.
- 2Each time the balance goes negative, it indicates a misplaced closing bracket.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.