We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Flip String to Monotone Increasing

Number: 962

Difficulty: Medium

Paid? No

Companies: Amazon, TikTok, IBM, Snap, Google


Problem Description

Given a binary string s, the task is to determine the minimum number of flips required to transform the string into a monotone increasing sequence, where all 0’s come before 1’s.


Key Insights

  • The string is monotone increasing if it contains some 0’s followed by some 1’s.
  • Each index decision involves whether to flip a '0' to a '1' or vice versa.
  • We can use a running count of ones seen so far while scanning from left to right.
  • For each '0', the cost could be to flip it to '1' or instead flip all preceding '1's to '0's.
  • A greedy approach or dynamic programming can solve this in one pass with constant space.

Space and Time Complexity

Time Complexity: O(n) Space Complexity: O(1)


Solution

The solution iterates through the string while maintaining a counter for the number of '1's encountered so far. For each character:

  • If the character is '1', increment the counter.
  • If the character is '0', consider two choices:
    1. Flip the '0' to '1' (increment the flip counter).
    2. Instead, flip all previously seen '1's to '0', which costs "onesCounter".
  • At each step, choose the minimum cost between these two strategies. This greedy/dynamic programming hybrid approach minimizes the overall flips by ensuring that at each position the best decision is taken based on the history of encountered characters.

Code Solutions

# Python solution for Flip String to Monotone Increasing

def minFlipsMonoIncr(s: str) -> int:
    # flips_count tracks the minimum flips needed so far
    flips_count = 0  
    # ones_counter counts the number of '1's encountered so far
    ones_counter = 0  
    
    # Iterate over each character in the string
    for char in s:
        # Check if the current character is '1'
        if char == '1':
            ones_counter += 1  # increment count for a '1'
        else:
            # If char is '0', decide to flip the current '0' or flip all previous '1's
            # Increase the flips counter for flipping current '0'
            flips_count += 1
            # Choose minimum between flipping current '0' and flipping all previous '1's
            flips_count = min(flips_count, ones_counter)
    return flips_count

# Example usage:
# print(minFlipsMonoIncr("00110"))
← Back to All Questions