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
- Type 1: move the first character to the end of the string.
- Type 2: flip any one character, 0 to 1 or 1 to 0.
Return the smallest number of type-2 operations needed. Type-1 operations are free and are not counted.
Example 1
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
Output: 0
Explanation: the string is already alternating.
Example 3
Output: 1
Explanation: flip the second character to get "1010".
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.
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, diffAdiffBdiffA = 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
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 diffAdiffB
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 diffAdiffB
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 diffAdiffB
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
- First, write the string twice with
. Set the countst = s + s anddiffA to 0, anddiffB tobest , the largestInteger.MAX_VALUE , so that any real count is smaller.int - A single loop moves
over all 2n positions ofi . At each position,t is the character pattern A has there: '0' at even positions and '1' at odd ones. IfexpectA differs fromt.charAt(i) , add 1 toexpectA ; otherwise add 1 todiffA .diffB - Once
reaches n, the character at positioni leaves the window. Compare it withi - n , the character pattern A has at that position, and subtract 1 from the count it added to.outExpectA - From
on, the window holds exactly n characters, which is one rotation ofi = n - 1 . If the smaller ofs anddiffA is belowdiffB , it becomes the newbest .best - After the last position,
holds the fewest flips over all n rotations, and the method returns it.best
The main
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:
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,
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
once, and each visit does at most two comparisons and two count updates.t - Space: O(n), because the doubled string
holds 2n characters. As an optional improvement, readingt instead ofs.charAt(i % n) gives the same characters without buildingt.charAt(i) , which brings the extra space down to O(1).t
Doubling a string to see all its rotations also solves