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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code