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
Binary String Segment CheckValid (≤1 segment)110"110" → trueInvalid (>1 segment)1001Pattern '01'"1001" → falseKey: Look for '01' pattern which indicates multiple segmentsIf '01' exists → Multiple segments → Return falseIf '01' not found → At most 1 segment → Return true
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
Asked in
Amazon 15 Microsoft 8
23.4K Views
Medium Frequency
~10 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