Minimum Changes To Make Alternating Binary String (LeetCode 1758): Solution and Explanation
Given a binary string s, return the fewest single-character flips that make it alternating, meaning no two neighbors are equal.
Intuition
An alternating string is fully determined by its first character. For a given length there are exactly two of them: 0101... and 1010....
So the question is how many positions of s disagree with each of those two targets, and which target is closer.
At every index the two targets hold opposite bits, so s matches exactly one of them there. That means the two mismatch counts always add up to n. Count mismatches against 0101... once and the other count is n minus it.
Approach: Count against one pattern
- Set
count = 0. - For each index i, the 0-start pattern holds
i % 2. Ifs[i]differs from it, increase count. - The 1-start pattern needs
n - countchanges. - Return
min(count, n - count).
Step-by-step example
s = "0100"
- Index 0: pattern wants 0, s has 0. Match.
- Index 1: pattern wants 1, s has 1. Match.
- Index 2: pattern wants 0, s has 0. Match.
- Index 3: pattern wants 1, s has 0. Mismatch, count = 1.
- Reaching 0101 takes 1 change and reaching 1010 takes 4 - 1 = 3. The answer is 1.
Code: Python, Java, C++
1class Solution:
2 def minOperations(self, s: str) -> int:
3 count = 0
4 for i in range(len(s)):
5 if int(s[i]) != i % 2:
6 count += 1
7 return min(count, len(s) - count)1class Solution {
2 public int minOperations(String s) {
3 int count = 0;
4 for (int i = 0; i < s.length(); i++) {
5 if (s.charAt(i) - '0' != i % 2) {
6 count++;
7 }
8 }
9 return Math.min(count, s.length() - count);
10 }
11}1class Solution {
2public:
3 int minOperations(string s) {
4 int count = 0;
5 for (int i = 0; i < (int)s.size(); i++) {
6 if (s[i] - '0' != i % 2) {
7 count++;
8 }
9 }
10 return min(count, (int)s.size() - count);
11 }
12};Time and space complexity
O(n)
One pass over the string with constant work per character.
O(1)
Only the counter is stored.
Other approaches
Count both patterns (time O(n), space O(1))
Keep two counters, one per target, and increase the right one at each index. Same answer and complexity; it just does not use the fact that the counts sum to n.
Build both targets (time O(n), space O(n))
Construct the strings 0101... and 1010... and compare each to s character by character. Easy to read but allocates two extra strings.
Common mistakes
- Greedily fixing each pair of equal neighbors as you meet them. Flipping one character can be locally right but commit you to the more expensive pattern; comparing against the two full targets avoids that.
- Only trying the pattern that starts with s[0]. For "1001011010", keeping the first 1 costs 6 changes while 0101010101 needs only 4.
- Comparing a character with an integer directly. Convert with
s[i] - '0'(or int(s[i])) before comparing withi % 2.
Frequently asked questions
Why do the two counts sum to n?
At each index the targets hold different bits and s holds one of them, so exactly one target disagrees with s at that index. Summed over all indexes that is n.
Can the answer be more than n / 2?
No. The two counts add to n, so the smaller one is at most n / 2.
Is a single character alternating?
Yes. With no neighbors there is nothing to conflict, so the answer for length 1 is 0.