Minimum Changes To Make Alternating Binary String (LeetCode 1758): Solution and Explanation

Easy
String
Counting

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

  1. Set count = 0.
  2. For each index i, the 0-start pattern holds i % 2. If s[i] differs from it, increase count.
  3. The 1-start pattern needs n - count changes.
  4. Return min(count, n - count).

Step-by-step example

s = "0100"
  1. Index 0: pattern wants 0, s has 0. Match.
  2. Index 1: pattern wants 1, s has 1. Match.
  3. Index 2: pattern wants 0, s has 0. Match.
  4. Index 3: pattern wants 1, s has 0. Mismatch, count = 1.
  5. 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)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

One pass over the string with constant work per character.

Space

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 with i % 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.