Python 1758.py
class Solution:
def minOperations(self, s: str) -> int:
# start with zero or one
zero = 0
one = 0
for i, c in enumerate(s):
if i & 1 == int(c):
one += 1
else:
zero += 1
return min(one, zero)
Difficulty
and has an acceptance rate of about 64% (200k+ submissions).
Typical patterns to solve this problem:
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The Solution.minOperations method computes the minimum number of character flips required to transform a binary string s into an alternating pattern. An alternating pattern is one where adjacent characters differ, which can start either with '0' or with '1'. The method evaluates both possibilities in a single pass and returns the smaller flip count.
Key Steps
The algorithm begins by establishing two counters, zero and one, both set to zero. These counters track the number of mismatches for the two alternating patterns: one that starts with '0' (zero) and one that starts with '1' (one).
zero = 0
one = 0
Next, the method iterates over each character c in the input string s, together with its index i. The index parity (even or odd) determines the expected character for each pattern. The expression i & 1 yields 0 for even positions and 1 for odd positions. By converting the character c to an integer (int(c)), the code can directly compare the expected parity with the actual character value.
for i, c in enumerate(s):
if i & 1 == int(c):
one += 1
else:
zero += 1
Inside the loop, the conditional i & 1 == int(c) identifies positions where the current character matches the expectation for the pattern that starts with '1'. When this condition holds, the one counter is incremented because a flip would be needed to conform to the opposite pattern (starting with '0'). Conversely, when the condition fails, the zero counter is incremented, indicating a mismatch for the pattern that starts with '0'.
After processing the entire string, the method selects the smaller of the two counters, representing the minimal flips required to achieve an alternating sequence, regardless of the starting character.
return min(one, zero)
Edge Cases Handled
The implementation gracefully handles an empty input string. Since the loop body never executes, both counters remain zero, and the method returns 0, indicating no flips are needed.
When the string consists of a single character, the parity check (i & 1) evaluates to 0. If the character is '0', the condition 0 == 0 is true, incrementing one and leaving zero unchanged; the final min yields 0, reflecting that the string already matches the pattern starting with '0'. If the character is '1', the condition fails, incrementing zero while one stays zero, and the result again is 0, because a single character also satisfies the alternating requirement when starting with '1'.
For strings where all characters are identical, the loop correctly counts mismatches for both possible starting patterns. The counters will accumulate the number of positions that deviate from each pattern, and the final min selects the lower count, which corresponds to flipping every other character to achieve alternation.
When the input already follows an alternating pattern, either starting with '0' or '1', the corresponding counter stays at zero throughout the iteration. The other counter may increase, but the min function ensures the method returns 0, indicating no operation is necessary.
Performance Optimizations
The algorithm processes the input string in a single linear pass, avoiding any auxiliary data structures beyond the two integer counters. This approach minimizes memory overhead and eliminates the need for multiple traversals.
Using the bitwise & operator to compute index parity (i & 1) is faster than a modulo operation (i % 2). The direct integer conversion of each character (int(c)) allows a simple equality comparison without additional branching or lookups.
By updating both counters within the same conditional block, the code reduces the number of conditional checks per iteration. The final min call operates on two scalar values, adding negligible cost.
Overall, the method achieves the desired result with minimal computational steps and constant extra space, making it well-suited for large input strings.
ELI5 - Simplified Explanation
Imagine you have a long row of colorful blocks. Each block has a letter either zero or one written on it. You want to make a special pattern where the numbers always take turns being different, like zero, one, zero, one and so on.
The code looks at every block in your row one by one. It acts like a helper who counts how many blocks need to change so the row looks just like the perfect pattern. The computer checks two different ways to make the row perfect. One way starts with a zero, and the other way starts with a one. It counts how many blocks would be wrong for each way. After looking at all of them, it figures out which way needs the smallest number of swaps to make everything match the pattern.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | Java | Go | C | Rust | TS | |||
| Progiez | C++ | Python | Java | |||||||
| github | black-shadows | C++ | ||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fsq | C++ | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| Krazune | C++ | |||||||||
| lkwq007 | Python | |||||||||
| MacJim | C++ | |||||||||
| pruthvikp | Python | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| withaarzoo | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C, C++, Go, Java, Python, Rust, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fsq | C++ | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| Krazune | C++ | |||||||||
| lkwq007 | Python | |||||||||
| MacJim | C++ | |||||||||
| pruthvikp | Python | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| withaarzoo | C++ |
Videos
Similar Problems
- problem 2957: Remove Adjacent Almost-Equal Characters
Solved On The Same Day
- problem 1365: How Many Numbers Are Smaller Than the Current Number
- problem 1389: Create Target Array in the Given Order
- problem 1394: Find Lucky Integer in an Array
- problem 1357: Apply Discount Every n Orders
- problem 1362: Closest Divisors
- problem 1367: Linked List in Binary Tree
- problem 1386: Cinema Seat Allocation
- problem 1390: Four Divisors
- problem 1395: Count Number of Teams
- problem 1759: Count Number of Homogenous Substrings
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality