Skip to content
← All posts

Check if Binary String Has at Most One Segment of Ones: Simple Scan Pattern

5 min read
leetcodeproblemeasystrings

You are given a binary string s (containing only '0' and '1'). The string does not contain leading zeros. Return true if s contains at most one contiguous segment of ones, and false otherwise.

This is LeetCode 1784: Check if Binary String Has at Most One Segment of Ones, and it is a great exercise in left-to-right scanning. The trick is recognizing that a second segment of ones can only appear if you see a '1' after a '0'.

101102one segment
s = "110". Green = ones forming a single contiguous segment. Result: true.

Why this problem matters

String scanning problems train you to think about transitions between characters. Instead of counting individual characters, you watch for patterns as you move through the string. Here, the pattern is simple: once you have seen a '0' after some '1's, any future '1' means there is a second segment.

This same "state tracking" idea appears in many problems. Whether you are detecting a mountain shape in an array, validating parentheses, or checking monotonicity, the skill is the same: you track what state you are in and react to transitions. Practicing it on a small, focused problem like this builds the reflex you need for harder variations.

The "no leading zeros" constraint also matters. Since the string always starts with '1', you know the first segment of ones begins at index 0. That simplifies the logic because you do not need to handle a leading '0' case.

The key insight

Because the string has no leading zeros, it always starts with one or more '1's. A valid string looks like 111...000..., one block of ones optionally followed by zeros. An invalid string looks like 111...000...111..., where ones appear again after a gap of zeros.

So you only need to check one thing: does the substring "01" appear anywhere in s? If it does, that means a '1' follows a '0', which means there is a second segment of ones. If it does not, all the ones are contiguous.

The algorithm:

  1. Scan the string from left to right.
  2. If you find the substring "01", return false.
  3. If you reach the end without finding "01", return true.

The solution

def check_ones_segment(s: str) -> bool:
    return "01" not in s

This one-liner captures the entire insight. Because the string has no leading zeros, it must start with '1'. The only way to have two separate segments of ones is if a '0' sits between them, which means "01" appears as a substring. The not in operator scans left to right and returns true if the pattern is absent.

You could also write this with an explicit loop for clarity:

def check_ones_segment(s: str) -> bool:
    for i in range(1, len(s)):
        if s[i] == '1' and s[i - 1] == '0':
            return False
    return True

This version checks each adjacent pair. If a '1' appears right after a '0', you have found the start of a second segment and return false immediately. If no such pair exists, you return true.

The "no leading zeros" constraint is doing a lot of work here. Without it, a string like "0110" would be valid (one segment of ones), but you would need extra logic to skip leading zeros before checking. Always read the constraints carefully because they often simplify the solution.

Visual walkthrough

Let's trace through several examples to see how the scan identifies single versus multiple segments of ones.

Example 1: s = "1" => true

10

Only one character, and it is a 1. One segment of ones. Return true.

Example 2: s = "110" => true

101102

Scanning left to right: ones at indices 0 and 1, then a zero. We never see a 1 after a 0. Return true.

Example 3: s = "1001" => false

10010213

After the first segment of ones, we hit zeros (orange). Then index 3 has another 1 (red), a second segment. Return false.

Example 4: s = "10" => true

1001

One segment of ones followed by a zero. No 1 appears after the zero. Return true.

In each case, the scan looks for a '1' that follows a '0'. If it finds one, there is a second segment and the answer is false. If the scan completes without finding that pattern, all ones are contiguous and the answer is true.

Complexity analysis

ApproachTimeSpace
Linear scanO(n)O(1)

Time is O(n) where n is the length of the string. The in operator (or the explicit loop) scans each character at most once. There is no nested iteration or repeated work.

Space is O(1). You are not building any auxiliary data structure. The scan uses only a constant amount of memory regardless of input size.

The building blocks

1. Substring presence check

"01" not in s

Checking whether a short pattern exists in a string is a fundamental operation. You use this in palindrome detection (checking reversed substrings), anagram problems (comparing frequency signatures), and any problem where a specific character sequence signals a condition. The in operator handles it cleanly in Python, but the underlying skill is knowing what to search for.

2. Adjacent pair comparison

for i in range(1, len(s)):
    if s[i] == '1' and s[i - 1] == '0':
        return False

Comparing each element with its neighbor is one of the most reusable patterns in string and array problems. You see it in monotonic checks, finding transitions, detecting duplicates, and computing differences. The loop starts at index 1 so you can always look back at i - 1 without going out of bounds.

Edge cases

  • Single character "1": only one character, which is a '1'. One segment. Return true.
  • All ones like "1111": no zeros at all, so "01" cannot appear. Return true.
  • Ones then zeros like "1100": classic valid case. One segment of ones followed by zeros. Return true.
  • Two segments like "1001": a zero gap between two groups of ones. "01" appears at index 2. Return false.
  • Alternating like "101": "01" appears at index 1. Return false.
  • Minimal invalid "10": one followed by zero. No second segment. Return true. Note "01" does not appear because the '0' is not followed by '1' here.

From understanding to recall

You have seen that this problem boils down to one check: does "01" appear in the string? The logic is clean and the code is minimal. But under interview pressure, you might overthink it and reach for counters, flags, or state machines when a single substring check is all you need.

Spaced repetition helps you internalize these clean patterns so they come to mind immediately. You practice recognizing the "no leading zeros" constraint, mapping it to the "01" insight, and writing the one-liner from memory. After a few rounds, you see "binary string, one segment" and the solution flows out without hesitation.

Related posts

CodeBricks breaks this problem into its substring check and adjacent pair comparison building blocks, then drills them independently with spaced repetition. You type each piece from scratch until the pattern is automatic. When a string scanning problem shows up in your interview, you do not think about it. You just write it.