Problem Statement

Given a binary string s containing only 0 and 1, the task is to find the minimum number of bit flips required to make the string alternating.

A binary string is called alternating when no two adjacent characters are the same.

A bit flip means changing:

  • 0 to 1
  • 1 to 0

The goal is to make the string alternating using the minimum number of flips.

Examples

Example 1:

Input: s = "001"

Output: 1

Explanation: By flipping the character at index 0, the string becomes "101", which is alternating. Therefore, only one flip is required.

Example 2:

Input: s = "0001010111"

Output: 2

Explanation: By flipping the characters at indices 1 and 8, the string becomes "0101010101", which is alternating. Therefore, the minimum number of flips required is 2.

Approach: Compare Two Alternating Patterns

An alternating binary string can only follow one of two patterns:

  • 010101010...
  • 101010101...

Instead of generating new strings, both patterns can be checked by comparing the expected character at each index with the actual character in the input string.

Two counters are maintained:

  • flip0 – counts the number of mismatches when the expected pattern starts with 0.
  • flip1 – counts the number of mismatches when the expected pattern starts with 1.

At every index, the expected character for both patterns is calculated using the index parity (i % 2).

After traversing the string, the smaller of the two flip counts is returned.

Step-by-step algorithm

  1. Initialize two counters, flip0 and flip1, to 0.
  2. Traverse the string from index 0 to s.Length - 1.
  3. For the first pattern (0101...):
    • At even indices, the expected character is 0.
    • At odd indices, the expected character is 1.
  4. For the second pattern (1010...):
    • At even indices, the expected character is 1.
    • At odd indices, the expected character is 0.
  5. If the actual character doesn't match the expected character, increment the corresponding counter.
  6. Return Math.Min(flip0, flip1).

C# Code

C#
class Solution
{
    public int minFlips(string s)
    {
        int flip0 = 0;
        int flip1 = 0;

        for (int i = 0; i < s.Length; i++)
        {
            char expected0 = (i % 2 == 0) ? '0' : '1';
            char expected1 = (i % 2 == 0) ? '1' : '0';

            if (s[i] != expected0)
                flip0++;

            if (s[i] != expected1)
                flip1++;
        }

        return Math.Min(flip0, flip1);
    }
}

Code Explanation

1. Initialize the counters

C#
int flip0 = 0;
int flip1 = 0;

Two integer variables are created to count the required flips for the two possible alternating patterns.

  • flip0 tracks flips for 010101....
  • flip1 tracks flips for 101010....

2. Traverse the string

C#
for (int i = 0; i < s.Length; i++)

The loop traverses each character of the string exactly once. The index i is used to determine whether the current position is even or odd.

3. Calculate the expected characters

C#
char expected0 = (i % 2 == 0) ? '0' : '1';
char expected1 = (i % 2 == 0) ? '1' : '0';

The modulo operator % is used to determine the parity of the index.

  • If i % 2 == 0, the index is even.
  • Otherwise, the index is odd.

The ternary operator ? : assigns the expected character based on the index.

IndexPattern 1 (0101...)Pattern 2 (1010...)
001
110
201
310
401

4. Count mismatches

C#
if (s[i] != expected0)
    flip0++;

if (s[i] != expected1)
    flip1++;

If the actual character doesn't match the expected character of a pattern, one flip is required for that position.

The counters are incremented independently for each pattern.

5. Return the minimum

C#
return Math.Min(flip0, flip1);

Math.Min() compares both flip counts and returns the smaller value, which represents the minimum number of flips required to make the string alternating.

Dry Run

Input: s = "001"

We compare the input string with both alternating patterns.

Pattern 1: 010

IndexActualExpectedFlip?
000No
101Yes
210Yes

Total flips for Pattern 1 = 2

Pattern 2: 101

IndexActualExpectedFlip?
001Yes
100No
211No

Total flips for Pattern 2 = 1

Therefore:

Minimum flips = Math.Min(2, 1)

Answer: 1

Dry Run – Example 2

Input: s = "0001010111"

PatternAlternating StringMismatches
Pattern 101010101012
Pattern 210101010108

The first pattern requires only two flips, whereas the second pattern requires eight flips.

Answer: 2

Why does this approach work?

Every alternating binary string must start with either 0 or 1. Once the starting character is selected, all the remaining characters are fixed because each character must be different from the previous one.

Therefore, there are exactly two possible alternating patterns for a given string length.

By counting the mismatches for both patterns and selecting the smaller count, the minimum number of flips is guaranteed to be found.

Complexity Analysis

  • Time Complexity: O(n) – The string is traversed once, and each character is compared with the expected characters of both patterns. Here, n is the length of the string.
  • Auxiliary Space: O(1) – Only a constant number of variables are used. No additional arrays or strings are created.

Key Takeaways

  • An alternating binary string has only two possible patterns.
  • i % 2 helps identify even and odd positions.
  • The ternary operator can determine expected characters efficiently.
  • Math.Min() selects the smaller number of flips.
  • The solution uses a single traversal with constant extra space.