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

Longer Contiguous Segments of Ones than Zeros

Number: 1999

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given a binary string s, determine if the longest contiguous segment of 1's is strictly longer than the longest contiguous segment of 0's. If it is, return true; otherwise, return false.


Key Insights

  • We need to find the maximum length of consecutive 1's and the maximum length of consecutive 0's.
  • The problem can be solved by iterating over the string and maintaining counters for current segments.
  • Alternatively, the string can be split by '0' to get segments of 1's and by '1' to get segments of 0's.
  • Edge cases to consider include strings with only one type of character.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the string. Space Complexity: O(1) if iterating through the string; using splitting might take extra space proportional to the number of segments.


Solution

We use an approach that either:

  1. Iterates through the string, maintaining running counts for consecutive 1's and 0's and updating the maximums accordingly, or
  2. Leverages string splitting methods to divide the string into segments of 1's or 0's and then uses a max function on the lengths.

Both approaches assure that we traverse the string in linear time while only keeping a few counters (constant space). The key is to correctly handle the transition between different characters so that each contiguous segment is accurately counted.


Code Solutions

def checkZeroOnes(s):
    # Split the string by '0' to isolate contiguous segments of ones.
    one_segments = s.split('0')
    # Get the length of the longest segment of ones.
    max_ones = max(len(segment) for segment in one_segments)
    
    # Split the string by '1' to isolate contiguous segments of zeros.
    zero_segments = s.split('1')
    # Get the length of the longest segment of zeros.
    max_zeros = max(len(segment) for segment in zero_segments)
    
    # Return True if the longest segment of ones is strictly greater than that of zeros.
    return max_ones > max_zeros

# Example usage:
print(checkZeroOnes("1101"))  # Expected output: True
← Back to All Questions