#1758
Minimum Changes To Make Alternating Binary String
EasyStringTwo PointersSliding Window
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of generating two strings, we can simply count how many changes are needed while traversing the string once. This reduces the time complexity significantly.
⚙️
Algorithm
4 steps- 1Step 1: Initialize two counters for changes needed for both patterns (starting with '0' and starting with '1').
- 2Step 2: Traverse the string character by character.
- 3Step 3: For each character, check if it matches the expected character for both patterns and increment the respective counters if it doesn't.
- 4Step 4: Return the minimum of the two counters.
solution.py13 lines
1# Full working Python code
2
3def min_operations(s):
4 count0 = 0
5 count1 = 0
6 for i in range(len(s)):
7 expected_char_for_0 = '0' if i % 2 == 0 else '1'
8 expected_char_for_1 = '1' if i % 2 == 0 else '0'
9 if s[i] != expected_char_for_0:
10 count0 += 1
11 if s[i] != expected_char_for_1:
12 count1 += 1
13 return min(count0, count1)ℹ
Complexity note: The time complexity is O(n) because we only make a single pass through the string, and the space complexity is O(1) since we use a fixed number of counters.
- 1The string can only be made alternating by changing adjacent characters.
- 2There are only two valid alternating patterns: starting with '0' or starting with '1'.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.