LeetCode 1888, Medium. Topics: String, Dynamic Programming, Sliding Window. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 28 parametrized pytest cases, and a playground notebook:
Problem
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.
Examples
Constraints
1 <= s.length <= 10^5
s[i] is either '0' or '1'.
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
NeetCode All. Last modified on September 7, 2026