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 - One Segment of Ones Check INPUT Binary String s: 1 idx 0 0 idx 1 0 idx 2 1 idx 3 Segments of 1s: Seg 1 Seg 2 Input: s = "1001" No leading zeros Length = 4 characters Contains: two 1s, two 0s ALGORITHM STEPS 1 Pattern Detection Look for "01" pattern in the string 2 Scan String Check if "01" exists after first segment "1001".contains("01") Found at index 2! 3 Analyze Pattern "01" means: 0 followed by new segment of 1s 4 Return Result If "01" found --> multiple segments exist Time: O(n) | Space: O(1) FINAL RESULT Analysis Complete: Segment 1: "1" 1 Segment 2: "1" Output: false Multiple segments of 1s detected (2 segments found) NOT OK - Return false Key Insight: The pattern "01" indicates a transition from 0 back to 1, meaning a new segment of ones has started. Since the string has no leading zeros, if "01" exists anywhere, there must be multiple segments. Simple check: return !s.contains("01") -- if "01" is found, return false; otherwise return true. TutorialsPoint - Check if Binary String Has at Most One Segment of Ones | Optimized - Pattern Detection
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