Number of flips to make binary string alternate

Pattern: Strings basics and frequency

easy

An alternating string is either 0101… or 1010…. Count the positions that differ from 0101…; the other pattern differs at exactly the remaining positions. The answer is the smaller count.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

You are given a string of 0s and 1s. A flip changes one character from 0 to 1 or back. Return the fewest flips that make the string alternate, so that no two neighbours are equal. For example, "001" needs 1 flip and "0001010111" needs 2.

This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name minFlips is this guide's own.

Think first

  • How many alternating strings of length n are there?
  • For one of them, how many flips does s need?
  • If a position matches one pattern, what about the other?

Hints

    Brute force, and why it fails

    Try flipping every subset of positions: exponential. Comparing with both patterns is O(n), and one pass is enough.

    The key insight

    The target is one of only two strings. Comparing against both, or against one and using n - k for the other, turns a search into counting.

    Dry run

    00 
    01 
    12 
    pattern010

    s = 001. Compare it with 010, the pattern that starts with 0.

    Step 1 of 4

    The plan

    k = 0
    for i from 0 to n - 1:
        want = '0' if i is even else '1'
        if s[i] != want: k = k + 1
    return min(k, n - k)
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    One pass with one counter.

    Edge cases

    • One character: 0 flips.
    • Already alternating: 0.
    • All equal, as in "1111": half the characters, 2.
    I've built my logic, show the code

    Java

    class Solution {
        public int minFlips(String s) {
            int startWith0 = 0;                     // flips needed to reach 0101...
            for (int i = 0; i < s.length(); i++) {
                char want = i % 2 == 0 ? '0' : '1';
                if (s.charAt(i) != want) startWith0++;
            }
            return Math.min(startWith0, s.length() - startWith0);   // 1010... needs exactly the other positions
        }
    }

    C++

    class Solution {
    public:
        int minFlips(string s) {
            int startWith0 = 0;                     // flips needed to reach 0101...
            for (size_t i = 0; i < s.size(); i++) {
                char want = i % 2 == 0 ? '0' : '1';
                if (s[i] != want) startWith0++;
            }
            return min(startWith0, static_cast<int>(s.size()) - startWith0);   // 1010... needs the other positions
        }
    };

    Python

    class Solution:
        def minFlips(self, s: str) -> int:
            start_with_0 = sum(1 for i, c in enumerate(s) if c != ("0" if i % 2 == 0 else "1"))   # flips to 0101...
            return min(start_with_0, len(s) - start_with_0)   # 1010... needs exactly the other positions

    Common mistakes

    • Checking only one pattern.
    • Flipping greedily whenever two neighbours match, which can use more flips than needed.
    • Counting mismatching pairs of neighbours instead of mismatching positions.

    Similar problems