Minimum Number of Flips to Make the Binary String Alternating

Find the fewest flips that make a binary string alternate, when rotating it is free.

Given a binary string s, a string made only of the characters 0 and 1, make it alternating with as few flips as possible. A string is alternating when no two neighbouring characters are equal, like "0101" or "10101". Two operations are allowed, as often as you like and in any order:

Return the smallest number of type-2 operations needed. Type-1 operations are free and are not counted.

Example 1
Input: s = "111000"
Output: 2
Explanation: move the first character to the end twice to get "100011", then flip the third and sixth characters to get "101010".
Example 2
Input: s = "010"
Output: 0
Explanation: the string is already alternating.
Example 3
Input: s = "1110"
Output: 1
Explanation: flip the second character to get "1010".
Solution

The Idea

Leave the free moves aside for a moment. How many flips does "1110" need? An alternating string of length 4 can only be "0101" or "1010", because once the first character is chosen, every next one is forced. Call the one starting with 0 pattern A and the one starting with 1 pattern B.

Compare "1110" with both, one position at a time. It differs from pattern A, "0101", in three positions, and from pattern B, "1010", only in the second. Flipping the characters that differ turns the string into that pattern, so the answer is 1, as in Example 3.

Now the free moves. A type-1 move takes the first character and puts it at the end, so "110" becomes "101", and then "011". Moving characters from the front to the back like this is called a rotation, and a string of length n has n of them. Rotations can save flips. "110" differs from pattern A, "010", in one position and from pattern B, "101", in two, so as it stands it needs 1 flip. Yet its rotation "101" is pattern B itself and needs none.

So the real question is which rotation needs the fewest flips. Building every rotation and comparing it with both patterns would work, but there is a way to see all the rotations at once. Write the string twice: "110" becomes "110110". Every rotation of "110" is a stretch of three neighbouring characters in it: "110" from position 0, "101" from position 1 and "011" from position 2. A stretch of fixed length that moves along a string one position at a time is called a window. Look at the picture below.

The string 110 written twice, 110110, lined up under pattern A, 010101, and pattern B, 101010. The window 110 has diffA 1 and diffB 2, the window 101 has diffA 0, and the window 011 has diffA 1 and diffB 2.

Under the position numbers, the first two rows are the two patterns, written six characters long. The rows below show "110110" three times, each with one window marked. Compare a window with the pattern cells right above it. Any three neighbouring cells of pattern A alternate too, so they form one of the two alternating strings of length 3, and the same holds for pattern B.

On the right, diffA counts the positions where the window differs from pattern A, and diffB the positions where it differs from pattern B. The smaller of the two is the number of flips that rotation needs. The row labelled window "101" has diffA = 0, so this rotation needs no flips, and the answer for "110" is 0.

Notice also what happens between two neighbouring rows: the window drops one character on its left and takes in one on its right. The other characters stay, so the two counts can be updated instead of recounted. Moving a window along a string while keeping its counts up to date this way is called the sliding window technique.

Solution Approach

Turning that idea into code means settling three things: how to reach every rotation, how many flips one window needs, and how to update the counts as the window slides.

Reaching every rotation

Why not rotate the string for real? Building one rotation and comparing it takes about n steps, and there are n rotations, so that is about n² steps: 1010 for a string of 100,000 characters. In the doubled string t = s + s, the window of length n that starts at position i is the string after i type-1 moves. So the windows starting at positions 0 to n - 1 cover every rotation.

Flips for one window

How many flips does one window need? It has to become one of the two alternating strings of its length, so the answer is the smaller of diffA and diffB. The two counts are linked. Pattern A and pattern B differ at every position, so each character matches exactly one of them. A character that differs from pattern A therefore matches pattern B, and a character that matches pattern A differs from pattern B. One test per character is enough to update both counts.

Updating the counts as the window slides

What changes when the window moves one step to the right? The character at the new right end enters, and the character n positions back leaves. The entering character adds 1 to diffA if it differs from pattern A at its position, and 1 to diffB otherwise. The leaving character takes back exactly what it added, with the same test at its own position. Each step costs the same small amount, however long the string is.

Even and odd lengths

Does rotation always matter? Only for strings of odd length. One type-1 move shifts every character one position to the left and sends the first character to position n - 1. In an even-length string, that changes every position from even to odd or back, so diffA and diffB simply swap and the smaller one stays the same.

Example 1 is such a case: "111000" differs from pattern B, "101010", only at positions 1 and 4, so it needs 2 flips without any rotation. In an odd-length string, the first character moves from position 0 to position n - 1, both even, while all the others switch between even and odd. That one character keeps its count while the rest swap, which is how a rotation can lower the number of flips.

Java Solution

The method minFlips works in these steps:

  1. First, write the string twice with t = s + s. Set the counts diffA and diffB to 0, and best to Integer.MAX_VALUE, the largest int, so that any real count is smaller.
  2. A single loop moves i over all 2n positions of t. At each position, expectA is the character pattern A has there: '0' at even positions and '1' at odd ones. If t.charAt(i) differs from expectA, add 1 to diffA; otherwise add 1 to diffB.
  3. Once i reaches n, the character at position i - n leaves the window. Compare it with outExpectA, the character pattern A has at that position, and subtract 1 from the count it added to.
  4. From i = n - 1 on, the window holds exactly n characters, which is one rotation of s. If the smaller of diffA and diffB is below best, it becomes the new best.
  5. After the last position, best holds the fewest flips over all n rotations, and the method returns it.

The main method runs the three examples, then "110" from the picture, the one-character string "0", and the odd-length string "01001001101".

Java
public class MinimumNumberOfFlipsToMakeTheBinaryStringAlternate {

    public static int minFlips(String s) {
        int n = s.length();
        String t = s + s;                     // every rotation is a window of length n in t
        int diffA = 0;                        // mismatches with "0101..." in the window
        int diffB = 0;                        // mismatches with "1010..." in the window
        int best = Integer.MAX_VALUE;
        for (int i = 0; i < 2 * n; i++) {
            char expectA = (i % 2 == 0) ? '0' : '1';
            if (t.charAt(i) != expectA) {
                diffA++;
            } else {
                diffB++;                      // a match with one pattern is a miss for the other
            }
            if (i >= n) {                     // character i - n leaves the window
                char outExpectA = ((i - n) % 2 == 0) ? '0' : '1';
                if (t.charAt(i - n) != outExpectA) {
                    diffA--;
                } else {
                    diffB--;
                }
            }
            if (i >= n - 1) {                 // the window holds n characters
                best = Math.min(best, Math.min(diffA, diffB));
            }
        }
        return best;
    }

    public static void main(String[] args) {
        System.out.println(minFlips("111000"));
        System.out.println(minFlips("010"));
        System.out.println(minFlips("1110"));
        System.out.println(minFlips("110"));
        System.out.println(minFlips("0"));
        System.out.println(minFlips("01001001101"));
    }
}

Running it prints:

Output
2
0
1
0
0
2

Look at the fourth line: "110" gives 0, found in the window "101" from the picture, although the string as given needs 1 flip. The fifth line is 0 because a single character has no neighbours, so "0" already alternates.

The last line shows how much rotation can save. "01001001101" has 11 characters, and as given it differs from the closer pattern in 5 positions. One of its rotations needs only 2 flips, and the method finds it. A solution that ignores type-1 moves would print 5 here.

The original implementation, MinimumNumberOfFlipsToMakeTheBinaryStringAlternate.java, is on GitHub.

Complexity

The work is one pass over the doubled string, with a fixed amount of work at each position.

  • Time: O(n), because the loop visits each of the 2n characters of t once, and each visit does at most two comparisons and two count updates.
  • Space: O(n), because the doubled string t holds 2n characters. As an optional improvement, reading s.charAt(i % n) instead of t.charAt(i) gives the same characters without building t, which brings the extra space down to O(1).

Doubling a string to see all its rotations also solves Rotate String.