Longer Contiguous Segments of Ones than Zeros - Problem

Given a binary string s, return true if the longest contiguous segment of 1's is strictly longer than the longest contiguous segment of 0's in s, or return false otherwise.

For example, in s = "110100010" the longest continuous segment of 1s has length 2, and the longest continuous segment of 0s has length 3.

Note that if there are no 0's, then the longest continuous segment of 0's is considered to have a length 0. The same applies if there is no 1's.

Input & Output

Example 1 — Mixed Segments
$ Input: s = "110100010"
Output: false
💡 Note: Longest segment of 1s has length 2 (positions 0-1), longest segment of 0s has length 3 (positions 4-6). Since 2 ≤ 3, return false.
Example 2 — 1s Win
$ Input: s = "1111000"
Output: true
💡 Note: Longest segment of 1s has length 4 (positions 0-3), longest segment of 0s has length 3 (positions 4-6). Since 4 > 3, return true.
Example 3 — All Ones
$ Input: s = "111"
Output: true
💡 Note: Only 1s present with length 3, no 0s (length 0). Since 3 > 0, return true.

Constraints

  • 1 ≤ s.length ≤ 1000
  • s consists only of '0' and '1'

Visualization

Tap to expand
Longer Contiguous Segments of Ones than Zeros INPUT Binary String s: 1 1 0 1 0 0 0 1 0 0 1 2 3 4 5 6 7 8 = 1 (ones) = 0 (zeros) Contiguous Segments: Ones: [11], [1], [1] Lengths: 2, 1, 1 Max: 2 Zeros: [0], [000], [0] Lengths: 1, 3, 1 Max: 3 s = "110100010" ALGORITHM STEPS 1 Initialize Counters max1=0, max0=0, cur1=0, cur0=0 2 Scan Each Character If '1': cur1++, cur0=0 If '0': cur0++, cur1=0 3 Update Maximums max1 = max(max1, cur1) max0 = max(max0, cur0) 4 Compare Results Return max1 > max0 Single Pass Tracking: i char cur1 cur0 max 0-1 11 2 0 2,0 4-6 000 0 3 2,3 End max1=2 max0=3 FINAL RESULT Length Comparison: 2 max1 3 max0 Is max1 (2) > max0 (3)? NO! 2 is NOT greater than 3 Output: false Longest 0s segment (3) is longer than 1s (2) Key Insight: Single pass O(n) solution: Track current and maximum lengths for both 1s and 0s simultaneously. When we see a '1', reset the 0-counter; when we see a '0', reset the 1-counter. Update max at each step. Space complexity O(1) - only need 4 integer variables to track all necessary information. TutorialsPoint - Longer Contiguous Segments of Ones than Zeros | Single Pass Approach
Asked in
Google 15 Amazon 12 Meta 8
12.5K Views
Medium Frequency
~8 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen