You are given a binary string s. You are allowed to perform two types of operations on the string in any sequence:
Type-1: Remove the character at the start of the string s and append it to the end of the string.
Type-2: Pick any character in s and flip its value, i.e., if its value is '0' it becomes '1' and vice-versa.
Return the minimum number of type-2 operations you need to performsuch that sbecomes alternating.
The string is called alternating if no two adjacent characters are equal.
For example, the strings "010" and "1010" are alternating, while the string "0100" is not.
Example 1:
Input: s = "111000"
Output: 2
Explanation: Use the first operation two times to make s = "100011".
Then, use the second operation on the third and sixth elements to make s = "101010".
Example 2:
Input: s = "010"
Output: 0
Explanation: The string is already alternating.
Example 3:
Input: s = "1110"
Output: 1
Explanation: Use the second operation on the second element to make s = "1010".
Problem summary: You are given a binary string s. You are allowed to perform two types of operations on the string in any sequence: Type-1: Remove the character at the start of the string s and append it to the end of the string. Type-2: Pick any character in s and flip its value, i.e., if its value is '0' it becomes '1' and vice-versa. Return the minimum number of type-2 operations you need to perform such that s becomes alternating. The string is called alternating if no two adjacent characters are equal. For example, the strings "010" and "1010" are alternating, while the string "0100" is not.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Minimum Operations to Make the Array Alternating (minimum-operations-to-make-the-array-alternating)
Step 02
Core Insight
What unlocks the optimal approach
Note what actually matters is how many 0s and 1s are in odd and even positions
For every cyclic shift we need to count how many 0s and 1s are at each parity and convert the minimum between them for each parity
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1888: Minimum Number of Flips to Make the Binary String Alternating
class Solution {
public int minFlips(String s) {
int n = s.length();
String target = "01";
int cnt = 0;
for (int i = 0; i < n; ++i) {
if (s.charAt(i) != target.charAt(i & 1)) {
++cnt;
}
}
int ans = Math.min(cnt, n - cnt);
for (int i = 0; i < n; ++i) {
if (s.charAt(i) != target.charAt(i & 1)) {
--cnt;
}
if (s.charAt(i) != target.charAt((i + n) & 1)) {
++cnt;
}
ans = Math.min(ans, Math.min(cnt, n - cnt));
}
return ans;
}
}
// Accepted solution for LeetCode #1888: Minimum Number of Flips to Make the Binary String Alternating
func minFlips(s string) int {
n := len(s)
target := "01"
cnt := 0
for i := range s {
if s[i] != target[i&1] {
cnt++
}
}
ans := min(cnt, n-cnt)
for i := range s {
if s[i] != target[i&1] {
cnt--
}
if s[i] != target[(i+n)&1] {
cnt++
}
ans = min(ans, min(cnt, n-cnt))
}
return ans
}
# Accepted solution for LeetCode #1888: Minimum Number of Flips to Make the Binary String Alternating
class Solution:
def minFlips(self, s: str) -> int:
n = len(s)
target = "01"
cnt = sum(c != target[i & 1] for i, c in enumerate(s))
ans = min(cnt, n - cnt)
for i in range(n):
cnt -= s[i] != target[i & 1]
cnt += s[i] != target[(i + n) & 1]
ans = min(ans, cnt, n - cnt)
return ans
// Accepted solution for LeetCode #1888: Minimum Number of Flips to Make the Binary String Alternating
/**
* [1888] Minimum Number of Flips to Make the Binary String Alternating
*
* You are given a binary string s. You are allowed to perform two types of operations on the string in any sequence:
*
* Type-1: Remove the character at the start of the string s and append it to the end of the string.
* Type-2: Pick any character in s and flip its value, i.e., if its value is '0' it becomes '1' and vice-versa.
*
* Return the minimum number of type-2 operations you need to perform such that s becomes alternating.
* The string is called alternating if no two adjacent characters are equal.
*
* For example, the strings "010" and "1010" are alternating, while the string "0100" is not.
*
*
* Example 1:
*
* Input: s = "111000"
* Output: 2
* Explanation: Use the first operation two times to make s = "100011".
* Then, use the second operation on the third and sixth elements to make s = "10<u>1</u>01<u>0</u>".
*
* Example 2:
*
* Input: s = "010"
* Output: 0
* Explanation: The string is already alternating.
*
* Example 3:
*
* Input: s = "1110"
* Output: 1
* Explanation: Use the second operation on the second element to make s = "1<u>0</u>10".
*
*
* Constraints:
*
* 1 <= s.length <= 10^5
* s[i] is either '0' or '1'.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/minimum-number-of-flips-to-make-the-binary-string-alternating/
// discuss: https://leetcode.com/problems/minimum-number-of-flips-to-make-the-binary-string-alternating/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn min_flips(s: String) -> i32 {
0
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_1888_example_1() {
let s = "111000".to_string();
let result = 2;
assert_eq!(Solution::min_flips(s), result);
}
#[test]
#[ignore]
fn test_1888_example_2() {
let s = "010".to_string();
let result = 0;
assert_eq!(Solution::min_flips(s), result);
}
#[test]
#[ignore]
fn test_1888_example_3() {
let s = "1110".to_string();
let result = 1;
assert_eq!(Solution::min_flips(s), result);
}
}
// Accepted solution for LeetCode #1888: Minimum Number of Flips to Make the Binary String Alternating
function minFlips(s: string): number {
const n = s.length;
const target = '01';
let cnt = 0;
for (let i = 0; i < n; ++i) {
if (s[i] !== target[i & 1]) {
++cnt;
}
}
let ans = Math.min(cnt, n - cnt);
for (let i = 0; i < n; ++i) {
if (s[i] !== target[i & 1]) {
--cnt;
}
if (s[i] !== target[(i + n) & 1]) {
++cnt;
}
ans = Math.min(ans, cnt, n - cnt);
}
return ans;
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n × m)
Space
O(n × m)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.
Shrinking the window only once
Wrong move: Using `if` instead of `while` leaves the window invalid for multiple iterations.
Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.
Fix: Shrink in a `while` loop until the invariant is valid again.