#1888

Minimum Number of Flips to Make the Binary String Alternating

Medium
StringDynamic ProgrammingSliding WindowSliding WindowTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution leverages the fact that we only need to count mismatches at even and odd indices for two possible alternating patterns. This avoids the need for generating all shifts, significantly improving efficiency.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the number of '0's and '1's at even and odd indices for the original string.
  2. 2Step 2: Calculate the flips needed for both alternating patterns: starting with '0' and starting with '1'.
  3. 3Step 3: Return the minimum of the two calculated values.
solution.py10 lines
1def minFlips(s):
2    even0, even1, odd0, odd1 = 0, 0, 0, 0
3    for i, char in enumerate(s):
4        if i % 2 == 0:
5            if char == '0': even0 += 1
6            else: even1 += 1
7        else:
8            if char == '0': odd0 += 1
9            else: odd1 += 1
10    return min(even1 + odd0, even0 + odd1)

Complexity note: The time complexity is O(n) because we only iterate through the string once to count the mismatches. The space complexity is O(1) since we use a fixed number of variables.

  • 1Understanding the structure of the string is crucial; we only need to focus on even and odd indices.
  • 2Cyclic shifts can be avoided by counting mismatches directly.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.