Check if Binary String Has at Most One Segment of Ones - Problem

Given a binary string s without leading zeros, determine if the string contains at most one contiguous segment of ones.

A contiguous segment means consecutive '1' characters that are not separated by any '0' characters. For example:

  • "1111" has one segment of ones
  • "101" has two segments of ones
  • "1100" has one segment of ones

Return true if the string has at most one contiguous segment of ones, otherwise return false.

Key insight: Since there are no leading zeros, if there are multiple segments of ones, we must encounter the pattern "01" somewhere in the string (a '0' followed by a '1').

Input & Output

example_1.py โ€” Basic case with one segment
$ Input: s = "1111"
โ€บ Output: true
๐Ÿ’ก Note: The string contains only consecutive '1's forming exactly one contiguous segment.
example_2.py โ€” Multiple segments
$ Input: s = "101"
โ€บ Output: false
๐Ÿ’ก Note: The string has two separate segments of '1's: one at position 0 and another at position 2, separated by '0' at position 1.
example_3.py โ€” One segment followed by zeros
$ Input: s = "1100"
โ€บ Output: true
๐Ÿ’ก Note: The string has one contiguous segment of '1's at the beginning, followed by '0's. This counts as having at most one segment.

Constraints

  • 1 โ‰ค s.length โ‰ค 100
  • s[i] is either '0' or '1'
  • s does not contain leading zeros (first character is always '1')

Visualization

Tap to expand
Binary String Segment Analysisโœ“ Valid: One Segment Only11100Pattern: 11100 - No '01' foundโœ— Invalid: Multiple Segments1101101 Found!Pattern: 11011 - '01' detectedAlgorithm VisualizationStep 1: Scan for '01' Patternfor i in range(len(s) - 1):if s[i] == '0' and s[i+1] == '1':return False # Multiple segments foundreturn True # At most one segmentTime: O(n), Space: O(1)Early termination on first '01' found
Understanding the Visualization
1
Understand the Pattern
Since no leading zeros exist, string must start with '1'
2
Identify Key Insight
Multiple segments require reconnecting: 111...000...111
3
Look for Evidence
Any '01' substring proves multiple segments exist
4
Early Termination
Return false immediately when '01' is found
Key Takeaway
๐ŸŽฏ Key Insight: Since there are no leading zeros, any '01' pattern proves multiple segments exist - making this an O(n) pattern matching problem rather than a segment counting problem.
Asked in
Amazon 15 Google 12 Microsoft 8 Meta 6
28.4K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen