Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

1888. Minimum Number of Flips to Make the Binary String Alternating - Leetcode Solution

Problem Description

Given a binary string s (a string consisting only of '0's and '1's), your task is to determine the minimum number of character flips required to make s alternating. An alternating binary string is one where no two adjacent characters are the same; for example, "0101" or "1010". Each flip changes a '0' to '1' or a '1' to '0'.

Constraints:

  • Each character in s is either '0' or '1'.
  • You may flip any character any number of times, but each flip counts towards your total.
  • The goal is to minimize the total number of flips.
  • There is always at least one valid solution.

Thought Process

At first glance, you might think about checking all possible combinations of flips, but this would be inefficient for long strings. Instead, notice that for an alternating string of length n, there are only two possible patterns:

  • Pattern 1: Starts with '0' (i.e., "010101...")
  • Pattern 2: Starts with '1' (i.e., "101010...")
For each pattern, you can count how many positions in s do not match the pattern and thus need to be flipped. The answer is the minimum of the two counts.

This realization shifts our approach from brute-force (trying all flip combinations) to a simple linear scan, comparing s against both possible alternating patterns.

Solution Approach

We solve the problem by:

  1. Generating two target patterns of the same length as s:
    • One that starts with '0' (let's call it alt1)
    • One that starts with '1' (let's call it alt2)
  2. Iterating through s and counting the number of positions where s differs from alt1 (flips1), and where it differs from alt2 (flips2).
  3. Returning the minimum of flips1 and flips2 as the answer.

We use simple iteration and comparison, making the solution efficient and easy to implement. Since we only need to compare each character once, the approach is optimal for this problem.

Example Walkthrough

Example: Suppose s = "10010100"

  • Pattern 1 (alt1): "01010101"
  • Pattern 2 (alt2): "10101010"
Step-by-step comparison:
Index s alt1 alt2 Mismatch alt1? Mismatch alt2?
0101YesNo
1010YesNo
2001NoYes
3110NoYes
4001NoYes
5110NoYes
6001NoYes
7010YesNo

Counting mismatches:

  • flips1 (compared to alt1): 3 mismatches (indices 0, 1, 7)
  • flips2 (compared to alt2): 5 mismatches (indices 2, 3, 4, 5, 6)
Answer: The minimum number of flips is 3.

Time and Space Complexity

Brute-force approach: Trying all possible flip combinations would take O(2n) time, which is infeasible for large n.

Optimized approach (the one described above):

  • Time Complexity: O(n), where n is the length of s, since we scan the string once.
  • Space Complexity: O(1) extra space (not counting input and output), since we only use a few counters. If you explicitly build the two patterns, it would be O(n), but you can generate the expected character on the fly.

Summary

The key insight is that an alternating binary string of length n can only have two forms: starting with '0' or with '1'. By counting mismatches against both, we find the minimal number of flips required. This approach is simple, efficient, and avoids unnecessary computation, making it a classic example of reducing a problem to a small set of possibilities and checking each directly.

Code Implementation

def minFlips(s: str) -> int:
    flips1 = flips2 = 0
    for i, c in enumerate(s):
        expected1 = '0' if i % 2 == 0 else '1'
        expected2 = '1' if i % 2 == 0 else '0'
        if c != expected1:
            flips1 += 1
        if c != expected2:
            flips2 += 1
    return min(flips1, flips2)
    
class Solution {
public:
    int minFlips(string s) {
        int flips1 = 0, flips2 = 0;
        for (int i = 0; i < s.size(); ++i) {
            char expected1 = (i % 2 == 0) ? '0' : '1';
            char expected2 = (i % 2 == 0) ? '1' : '0';
            if (s[i] != expected1) flips1++;
            if (s[i] != expected2) flips2++;
        }
        return min(flips1, flips2);
    }
};
    
class Solution {
    public int minFlips(String s) {
        int flips1 = 0, flips2 = 0;
        for (int i = 0; i < s.length(); i++) {
            char expected1 = (i % 2 == 0) ? '0' : '1';
            char expected2 = (i % 2 == 0) ? '1' : '0';
            if (s.charAt(i) != expected1) flips1++;
            if (s.charAt(i) != expected2) flips2++;
        }
        return Math.min(flips1, flips2);
    }
}
    
function minFlips(s) {
    let flips1 = 0, flips2 = 0;
    for (let i = 0; i < s.length; i++) {
        let expected1 = i % 2 === 0 ? '0' : '1';
        let expected2 = i % 2 === 0 ? '1' : '0';
        if (s[i] !== expected1) flips1++;
        if (s[i] !== expected2) flips2++;
    }
    return Math.min(flips1, flips2);
}