Problem 1888 · LeetCode 1888(opens in a new tab)
Minimum Number of Flips to Make the Binary String Alternating
MediumSliding windows
You get a string s of 0s and 1s and two kinds of moves. A shift takes the first character off the front and puts it on the back. A flip changes one character, 0 to 1 or 1 to 0.
A string is alternating when no two neighbours are equal, like "1010" or "01010". Shifts are free. Return the fewest flips needed to make s alternating, using as many shifts as you like, in any order.
Example 1
Input: s = "11010" Output: 0 Why: one shift gives "10101", which already alternates
2 more examples and the constraints
Example 2
Input: s = "00110" Output: 1 Why: shift 3 times to "10001", then flip the middle 0
Example 3
Input: s = "0100" Output: 1 Why: flip the last character to get "0101"
Constraints
- 1 ≤ s.length ≤ 100,000
- Each s[i] is '0' or '1'
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Try every rotationO(n²)
- Slide a window over s + sO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Character checks for a string of 100,000 | Verdict |
|---|---|---|---|
| Try every rotation | O(n²) | Times out | |
| Slide a window over s + s | O(n) | Best; one pass of 2n |
n = length of s.
Edge cases to test
- One character. "0" or "1" already alternates: 0 flips.
- Already alternating. "1010" needs 0 flips, with or without shifts.
- Even length. Shifts cannot help: "0100" still needs 1 flip.
- Odd length. Shifting can save flips: "11010" needs 0 after one shift.
- All the same. "1111" needs 2 flips; "000" needs 1.
Common mistakes
- Checking only the pattern that starts with 0 and forgetting n - diff for the one that starts with 1.
- Updating best before the first window is full, which counts windows shorter than n.
- Subtracting the leaving character using the current index's target instead of its own position in the pattern.
How to talk through it
- 1Clarify. Do shifts cost anything? Is the answer only the number of flips?
- 2Reduce it. Free shifts mean picking a rotation, then flipping against one of two targets.
- 3Give the brute force. Count mismatches for all n rotations; O(n²).
- 4Slide. Rotations are windows of s + s, so keep a running mismatch count.
- 5Test out loud. Run one character, an even length, and an odd length where a shift helps.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?