DEV Community

Dolly Sharma
Dolly Sharma

Posted on

LeetCode 1784 – Check if Binary String Has at Most One Segment of Ones (Day-06)

A very interesting string observation problem from LeetCode that can be solved in one line using find() in C++.

Problem

You are given a binary string s without leading zeros.

Return true if the string contains at most one contiguous segment of '1's, otherwise return false.

Example

Input:  "1001"
Output: false
Enter fullscreen mode Exit fullscreen mode

Explanation:

1 000 1
Enter fullscreen mode Exit fullscreen mode

There are two segments of ones, so the answer is false.

Another example:

Input: "11100"
Output: true
Enter fullscreen mode Exit fullscreen mode

There is only one segment of ones.


Key Observation

If a binary string has more than one segment of ones, there must be a pattern:

01
Enter fullscreen mode Exit fullscreen mode

Why?

Because after the first segment of 1s ends, we see:

1 → 0
Enter fullscreen mode Exit fullscreen mode

And when another 1 starts again, the string must contain:

01
Enter fullscreen mode Exit fullscreen mode

Example:

1001
   ↑
  "01"
Enter fullscreen mode Exit fullscreen mode

So the trick is simple:

If "01" exists in the string, then there are multiple segments of ones.


3 Elegant One-Line Solution

class Solution {
public:
    bool checkOnesSegment(string s) {
        return s.find("01") == string::npos;
    }
};
Enter fullscreen mode Exit fullscreen mode

Explanation

string::npos means pattern not found.

So:

s.find("01") == string::npos
Enter fullscreen mode Exit fullscreen mode

means

"01" does NOT exist in the string
Enter fullscreen mode Exit fullscreen mode

Therefore the string has at most one contiguous segment of ones.


Complexity

Time Complexity

O(n)
Enter fullscreen mode Exit fullscreen mode

Space Complexity

O(1)
Enter fullscreen mode Exit fullscreen mode

Interview Insight

Instead of counting segments manually, notice the pattern transition:

1 → 0 → 1
Enter fullscreen mode Exit fullscreen mode

The substring "01" reveals the start of another segment of ones.

Recognizing such pattern-based shortcuts is a powerful trick in coding interviews.

Top comments (0)