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

Difficulty: Easy


Problem Description

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


Key Insights

  • We need to identify the lengths of the longest contiguous segments of both '1's and '0's.
  • If the string contains no '0's, the longest segment of '0's is considered to have length 0, and vice versa for '1's.
  • A single traversal of the string can be used to count the lengths of the segments.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(1), as we are using a constant amount of space for counting lengths.


Solution

To solve the problem, we will traverse the string once while maintaining two variables to track the longest contiguous segments of '1's and '0's. We will iterate through each character in the string, counting lengths of segments until we encounter a different character, at which point we compare and potentially update our longest segment lengths. Finally, we will compare the two lengths and return the result.


Code Solutions

def checkZeroOnes(s: str) -> bool:
    max_ones = max_zeros = current_count = 0
    current_char = s[0]

    for char in s:
        if char == current_char:
            current_count += 1
        else:
            if current_char == '1':
                max_ones = max(max_ones, current_count)
            else:
                max_zeros = max(max_zeros, current_count)
            current_char = char
            current_count = 1

    # Final check for the last segment
    if current_char == '1':
        max_ones = max(max_ones, current_count)
    else:
        max_zeros = max(max_zeros, current_count)

    return max_ones > max_zeros
← Back to All Questions