Check if Binary String Has at Most One Segment of Ones (LeetCode 1784): Solution and Explanation

Easy
String

Given a binary string that starts with '1', decide whether all of its ones form one contiguous block.

Intuition

Because the string has no leading zeros, the first block of ones always starts at index 0. The only question is whether another block appears later.

A new block of ones can only begin at a '1' that sits right after a '0'. So a second segment exists exactly when the two characters "01" appear next to each other somewhere in the string.

Approach: Scan neighboring pairs for "01"

  1. Walk i from 1 to n - 1 and look at the pair s[i - 1], s[i].
  2. If the pair is "01", a second run of ones starts at i, so return false.
  3. If the loop ends without finding "01", return true.

Step-by-step example

s = "1001"
  1. The string starts with '1', so run 1 begins at index 0.
  2. Pair (0, 1) is "10": the first run ends.
  3. Pair (1, 2) is "00": still in the zeros.
  4. Pair (2, 3) is "01": a second run starts at index 3, so the answer is false.

Code: Python, Java, C++

1class Solution:
2    def checkOnesSegment(self, s: str) -> bool:
3        for i in range(1, len(s)):
4            if s[i - 1] == '0' and s[i] == '1':
5                return False
6        return True
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each neighboring pair is checked at most once, and the scan stops at the first "01".

Space

O(1)

Only the loop index is stored.

Other approaches

Substring search (time O(n), space O(1))

Return "01" not in s. It is the same idea expressed with the language's built-in search.

Count runs of ones (time O(n), space O(1))

Count how many times a '1' starts a run (index 0 or after a '0') and return whether the count is at most 1. This also works without the no-leading-zero guarantee.

Common mistakes

  • Looking for "10" instead of "01". The pair "10" only ends the first run, which is allowed.
  • Counting zeros. Trailing zeros like "1100" are fine; only a '1' after a zero matters.
  • Forgetting that a single '1' is one segment, so "1" returns true.

Frequently asked questions

Why does the missing leading zero matter?

It guarantees the first run starts at index 0, so every other run must begin with the pair "01". With leading zeros, a single run like "0011" would also contain "01" and the shortcut would fail.

Is a string with only one '1' valid?

Yes. One '1' is a segment of length one, so the answer is true.

Can the scan stop early?

Yes. The first "01" proves there are at least two segments, so you can return false immediately.