Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | Unknown |
| Space | O(1) | Unknown |
💡
Intuition
Time UnknownSpace Unknown
The optimal solution involves counting the number of '0's and '1's in the string. Based on their counts, we can determine if it's possible to form an alternating string and calculate the minimum swaps needed.
⚙️
Algorithm
4 steps- 1Step 1: Count the number of '0's and '1's in the string.
- 2Step 2: Check if the absolute difference between the counts is greater than 1. If so, return -1 (impossible to alternate).
- 3Step 3: Calculate the expected positions for '0's and '1's based on the counts.
- 4Step 4: Count mismatches for both expected patterns and return the minimum swaps needed.
solution.py14 lines
1def min_swaps(s):
2 count0 = s.count('0')
3 count1 = s.count('1')
4 if abs(count0 - count1) > 1:
5 return -1
6 swaps1 = swaps2 = 0
7 for i in range(len(s)):
8 expected = '01' if count0 >= count1 else '10'
9 if s[i] != expected[i % 2]:
10 swaps1 += 1
11 expected = '10' if count0 >= count1 else '01'
12 if s[i] != expected[i % 2]:
13 swaps2 += 1
14 return min(swaps1 // 2, swaps2 // 2)Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.