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
Explanation:
1 000 1
There are two segments of ones, so the answer is false.
Another example:
Input: "11100"
Output: true
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
Why?
Because after the first segment of 1s ends, we see:
1 → 0
And when another 1 starts again, the string must contain:
01
Example:
1001
↑
"01"
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;
}
};
Explanation
string::npos means pattern not found.
So:
s.find("01") == string::npos
means
"01" does NOT exist in the string
Therefore the string has at most one contiguous segment of ones.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)
Interview Insight
Instead of counting segments manually, notice the pattern transition:
1 → 0 → 1
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)