Check if Binary String Has at Most One Segment of Ones - Problem
Given a binary string s without leading zeros, return true if s contains at most one contiguous segment of ones. Otherwise, return false.
A contiguous segment of ones is a substring that contains only the character '1' and is surrounded by '0' characters or string boundaries.
Input & Output
Example 1 — Single Segment
$
Input:
s = "1001"
›
Output:
false
💡 Note:
There are two segments of ones: "1" at position 0, and "1" at position 3. Since there are more than one segment, return false.
Example 2 — Contiguous Segment
$
Input:
s = "110"
›
Output:
true
💡 Note:
There is only one contiguous segment of ones: "11" at positions 0-1. Return true.
Example 3 — All Ones
$
Input:
s = "1"
›
Output:
true
💡 Note:
The string contains only one character '1', which forms exactly one segment. Return true.
Constraints
- 1 ≤ s.length ≤ 100
- s[i] is either '0' or '1'
- s[0] == '1' (no leading zeros)
Visualization
Tap to expand
Understanding the Visualization
1
Input
Binary string without leading zeros
2
Process
Look for '01' pattern indicating multiple segments
3
Output
True if ≤1 segment, false if >1 segment
Key Takeaway
🎯 Key Insight: The pattern '01' can only exist if there are multiple segments of 1s separated by 0s
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code