algoadvance

You are given a binary string s (a string consisting only of ‘0’s and ‘1’s). You need to check if the binary string has at most one contiguous segment of ‘1’s. Return True if the string contains at most one segment of ‘1’s, otherwise return False.

Example:

Clarifying Questions

Strategy

To solve this problem, we’ll:

  1. Traverse the string looking for transitions between ‘0’ to ‘1’ and ‘1’ to ‘0’.
  2. Count the number of segments of ‘1’s.
  3. If the count of segments of ‘1’s is greater than 1, return False; otherwise, return True.

Code

def checkOnesSegment(s: str) -> bool:
    count_segments = 0
    in_segment = False
    
    for char in s:
        if char == '1':
            if not in_segment:
                count_segments += 1
                if count_segments > 1:
                    return False
                in_segment = True
        else:
            in_segment = False
                
    return True

# Example usage
print(checkOnesSegment("1001"))  # Output: False
print(checkOnesSegment("110"))   # Output: True

Time Complexity

Try our interview co-pilot at AlgoAdvance.com