Longer Contiguous Segments of Ones than Zeros - Problem
Given a binary string s, determine whether the longest contiguous segment of 1's is strictly longer than the longest contiguous segment of 0's.
A contiguous segment is a sequence of consecutive identical characters. For example:
- In
"110100010", the longest segment of 1's has length 2 ("11") - The longest segment of 0's has length 3 ("000")
- Since 2 < 3, we return
false
Special cases:
- If there are no 0's in the string, the longest segment of 0's is considered to have length 0
- If there are no 1's in the string, the longest segment of 1's is considered to have length 0
Return true if the longest segment of 1's is strictly longer than the longest segment of 0's, otherwise return false.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "1101"
โบ
Output:
true
๐ก Note:
The longest segment of 1's is "11" with length 2. The longest segment of 0's is "0" with length 1. Since 2 > 1, return true.
example_2.py โ Longer Zeros
$
Input:
s = "110100010"
โบ
Output:
false
๐ก Note:
The longest segment of 1's is "11" with length 2. The longest segment of 0's is "000" with length 3. Since 2 < 3, return false.
example_3.py โ Only Ones
$
Input:
s = "111"
โบ
Output:
true
๐ก Note:
The longest segment of 1's is "111" with length 3. There are no 0's, so the longest segment of 0's has length 0. Since 3 > 0, return true.
Visualization
Tap to expand
Understanding the Visualization
1
Initialize Tracking
Set up counters for current segment length and maximum lengths seen so far
2
Scan Characters
Move through each character, extending current segment or starting a new one
3
Update Records
When a segment ends, check if it beats the current record for that character type
4
Final Comparison
Compare the longest 1's segment with longest 0's segment to get the answer
Key Takeaway
๐ฏ Key Insight: By tracking segment lengths in a single pass, we can efficiently determine the winner without needing to store or re-examine any part of the string, achieving optimal O(n) time and O(1) space complexity.
Time & Space Complexity
Time Complexity
O(n)
Single pass through the string, examining each character exactly once
โ Linear Growth
Space Complexity
O(1)
Only using a constant number of variables regardless of input size
โ Linear Space
Constraints
- 1 โค s.length โค 500
- s consists only of characters '0' and '1'
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code