Check if Binary String Has at Most One Segment of Ones (LeetCode 1784): Solution and Explanation
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"
- Walk i from 1 to n - 1 and look at the pair s[i - 1], s[i].
- If the pair is "01", a second run of ones starts at i, so return
false. - If the loop ends without finding "01", return
true.
Step-by-step example
s = "1001"
- The string starts with '1', so run 1 begins at index 0.
- Pair (0, 1) is "10": the first run ends.
- Pair (1, 2) is "00": still in the zeros.
- 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 True1class Solution {
2 public boolean checkOnesSegment(String s) {
3 for (int i = 1; i < s.length(); i++) {
4 if (s.charAt(i - 1) == '0' && s.charAt(i) == '1') {
5 return false;
6 }
7 }
8 return true;
9 }
10}1class Solution {
2public:
3 bool checkOnesSegment(string s) {
4 for (int i = 1; i < (int)s.size(); i++) {
5 if (s[i - 1] == '0' && s[i] == '1') {
6 return false;
7 }
8 }
9 return true;
10 }
11};Time and space complexity
O(n)
Each neighboring pair is checked at most once, and the scan stops at the first "01".
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.