Facebook Pixel

1869. Longer Contiguous Segments of Ones than Zeros

EasyString
Leetcode Link

Problem Description

Given a binary string s (containing only '0's and '1's), you need to determine if the longest contiguous segment of '1's is strictly longer than the longest contiguous segment of '0's.

The task is to:

  1. Find the maximum length of consecutive '1's in the string
  2. Find the maximum length of consecutive '0's in the string
  3. Return true if the longest segment of '1's is strictly longer than the longest segment of '0's, otherwise return false

For example, in s = "110100010":

  • The longest consecutive segment of '1's is "11" with length 2
  • The longest consecutive segment of '0's is "000" with length 3
  • Since 2 is not greater than 3, the function returns false

Important notes:

  • If the string contains no '0's, the longest segment of '0's has length 0
  • If the string contains no '1's, the longest segment of '1's has length 0
  • The comparison must be strictly greater (>), not greater than or equal to

The solution uses a helper function f(x) that iterates through the string once to find the maximum length of consecutive occurrences of character x. It maintains a counter that increments when the current character matches x and resets to 0 when it doesn't, tracking the maximum count seen. The main function then compares f("1") with f("0") to determine the result.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

The key insight is that we need to find the maximum length of consecutive segments for both '1's and '0's separately, then compare them. This naturally suggests a pattern-matching approach where we track consecutive occurrences of the same character.

When we think about finding the longest consecutive segment of a specific character, we can visualize sliding through the string and counting how many times we see that character in a row. Whenever we encounter a different character, we know the current consecutive segment has ended, so we reset our counter and start fresh.

This leads us to the idea of using a counter that:

  • Increments when we see the target character
  • Resets to 0 when we see a different character
  • Keeps track of the maximum count seen so far

Since we need to do this same operation for both '1's and '0's, it makes sense to extract this logic into a reusable function f(x) that finds the longest consecutive segment of character x. This way, we avoid duplicating code and make the solution cleaner.

The beauty of this approach is its simplicity - we make two passes through the string (one for each character type), each pass using the same logic but looking for different characters. The time complexity remains linear O(n) since we're just doing two sequential scans, and the space complexity is O(1) as we only need a few variables to track counts.

Finally, once we have both maximum lengths, the answer is simply whether the maximum length of '1's is strictly greater than the maximum length of '0's.

Solution Approach

The solution implements a two-pass approach using a helper function to find the maximum consecutive length for each character type.

Helper Function f(x):

The function f(x) takes a character x (either '1' or '0') and returns the length of the longest consecutive segment of that character in the string:

  1. Initialize two variables:

    • cnt = 0: tracks the current consecutive count
    • mx = 0: stores the maximum consecutive count seen so far
  2. Iterate through each character c in the string s:

    • If c == x (current character matches target):
      • Increment cnt by 1
      • Update mx = max(mx, cnt) to keep track of the maximum
    • If c != x (current character doesn't match):
      • Reset cnt = 0 since the consecutive sequence is broken
  3. Return mx as the maximum consecutive length found

Main Logic:

The main function makes two calls to the helper function:

  • f("1"): finds the longest consecutive segment of '1's
  • f("0"): finds the longest consecutive segment of '0's

Finally, it returns the boolean result of f("1") > f("0").

Example Walkthrough:

For s = "110100010":

  • First pass with f("1"):

    • Characters: 1,1,0,1,0,0,0,1,0
    • cnt values: 1,2,0,1,0,0,0,1,0
    • mx updates to: 1,2,2,2,2,2,2,2,2
    • Returns 2
  • Second pass with f("0"):

    • Characters: 1,1,0,1,0,0,0,1,0
    • cnt values: 0,0,1,0,1,2,3,0,1
    • mx updates to: 0,0,1,1,1,2,3,3,3
    • Returns 3
  • Result: 2 > 3 is False

The algorithm runs in O(n) time complexity where n is the length of the string, as we traverse the string twice. The space complexity is O(1) as we only use a constant amount of extra space.

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through the solution with s = "1101110":

Step 1: Find the longest consecutive segment of '1's using f("1")

We'll traverse the string character by character:

  • Position 0: '1' → matches target '1', so cnt = 1, mx = 1
  • Position 1: '1' → matches target '1', so cnt = 2, mx = 2
  • Position 2: '0' → doesn't match '1', so cnt = 0, mx = 2 (unchanged)
  • Position 3: '1' → matches target '1', so cnt = 1, mx = 2 (unchanged)
  • Position 4: '1' → matches target '1', so cnt = 2, mx = 2 (unchanged)
  • Position 5: '1' → matches target '1', so cnt = 3, mx = 3 (updated!)
  • Position 6: '0' → doesn't match '1', so cnt = 0, mx = 3 (unchanged)

Result: f("1") returns 3 (the longest segment "111" has length 3)

Step 2: Find the longest consecutive segment of '0's using f("0")

Again traversing the string:

  • Position 0: '1' → doesn't match '0', so cnt = 0, mx = 0
  • Position 1: '1' → doesn't match '0', so cnt = 0, mx = 0
  • Position 2: '0' → matches target '0', so cnt = 1, mx = 1
  • Position 3: '1' → doesn't match '0', so cnt = 0, mx = 1 (unchanged)
  • Position 4: '1' → doesn't match '0', so cnt = 0, mx = 1 (unchanged)
  • Position 5: '1' → doesn't match '0', so cnt = 0, mx = 1 (unchanged)
  • Position 6: '0' → matches target '0', so cnt = 1, mx = 1 (unchanged)

Result: f("0") returns 1 (the longest segment of '0's has length 1)

Step 3: Compare the results

We check if f("1") > f("0"):

  • 3 > 1 evaluates to true

Therefore, the function returns true because the longest consecutive segment of '1's (length 3) is strictly longer than the longest consecutive segment of '0's (length 1).

Solution Implementation

1class Solution:
2    def checkZeroOnes(self, s: str) -> bool:
3        """
4        Check if the longest contiguous segment of 1s is strictly longer than 
5        the longest contiguous segment of 0s in a binary string.
6      
7        Args:
8            s: Binary string containing only '0' and '1' characters
9          
10        Returns:
11            True if longest sequence of 1s > longest sequence of 0s, False otherwise
12        """
13      
14        def find_max_consecutive_length(target_char: str) -> int:
15            """
16            Find the maximum length of consecutive occurrences of a target character.
17          
18            Args:
19                target_char: The character to find consecutive sequences of
20              
21            Returns:
22                Maximum length of consecutive occurrences
23            """
24            current_count = 0
25            max_length = 0
26          
27            # Iterate through each character in the string
28            for char in s:
29                if char == target_char:
30                    # Increment counter for consecutive matches
31                    current_count += 1
32                    # Update maximum if current sequence is longer
33                    max_length = max(max_length, current_count)
34                else:
35                    # Reset counter when sequence breaks
36                    current_count = 0
37                  
38            return max_length
39      
40        # Compare the maximum consecutive lengths of '1's and '0's
41        max_ones_length = find_max_consecutive_length("1")
42        max_zeros_length = find_max_consecutive_length("0")
43      
44        return max_ones_length > max_zeros_length
45
1class Solution {
2    /**
3     * Checks if the longest contiguous segment of 1s is strictly longer than 
4     * the longest contiguous segment of 0s in the binary string.
5     * 
6     * @param s The input binary string containing only '0' and '1' characters
7     * @return true if longest segment of 1s > longest segment of 0s, false otherwise
8     */
9    public boolean checkZeroOnes(String s) {
10        return findLongestSegment(s, '1') > findLongestSegment(s, '0');
11    }
12
13    /**
14     * Finds the length of the longest contiguous segment of a specific character.
15     * 
16     * @param s The input string to search
17     * @param targetChar The character to find consecutive occurrences of
18     * @return The maximum length of consecutive occurrences of targetChar
19     */
20    private int findLongestSegment(String s, char targetChar) {
21        int currentLength = 0;  // Tracks the current consecutive count
22        int maxLength = 0;      // Tracks the maximum consecutive count found
23      
24        // Iterate through each character in the string
25        for (int i = 0; i < s.length(); i++) {
26            if (s.charAt(i) == targetChar) {
27                // If character matches, increment current count and update max if needed
28                currentLength++;
29                maxLength = Math.max(maxLength, currentLength);
30            } else {
31                // If character doesn't match, reset current count
32                currentLength = 0;
33            }
34        }
35      
36        return maxLength;
37    }
38}
39
1class Solution {
2public:
3    bool checkZeroOnes(string s) {
4        // Lambda function to find the maximum consecutive length of a given character
5        auto findMaxConsecutiveLength = [&](char targetChar) {
6            int currentCount = 0;  // Current consecutive count of targetChar
7            int maxLength = 0;     // Maximum consecutive length found so far
8          
9            // Iterate through each character in the string
10            for (char& c : s) {
11                if (c == targetChar) {
12                    // If current character matches target, increment the count
13                    currentCount++;
14                    // Update maximum length if current count is greater
15                    maxLength = max(maxLength, currentCount);
16                } else {
17                    // Reset count when a different character is encountered
18                    currentCount = 0;
19                }
20            }
21          
22            return maxLength;
23        };
24      
25        // Check if the longest consecutive sequence of '1's is longer than 
26        // the longest consecutive sequence of '0's
27        return findMaxConsecutiveLength('1') > findMaxConsecutiveLength('0');
28    }
29};
30
1/**
2 * Checks if the longest contiguous segment of 1s is strictly longer than 
3 * the longest contiguous segment of 0s in a binary string
4 * @param s - Binary string containing only '0' and '1' characters
5 * @returns true if longest segment of 1s > longest segment of 0s, false otherwise
6 */
7function checkZeroOnes(s: string): boolean {
8    /**
9     * Finds the maximum length of contiguous segments for a given character
10     * @param targetChar - The character to search for ('0' or '1')
11     * @returns Maximum length of contiguous segment
12     */
13    const findMaxContiguousLength = (targetChar: string): number => {
14        let maxLength = 0;
15        let currentLength = 0;
16      
17        // Iterate through each character in the string
18        for (const char of s) {
19            if (char === targetChar) {
20                // Increment current segment length and update maximum if needed
21                currentLength++;
22                maxLength = Math.max(maxLength, currentLength);
23            } else {
24                // Reset current segment length when different character is found
25                currentLength = 0;
26            }
27        }
28      
29        return maxLength;
30    };
31  
32    // Compare the maximum contiguous lengths of 1s and 0s
33    return findMaxContiguousLength('1') > findMaxContiguousLength('0');
34}
35

Time and Space Complexity

The time complexity is O(n), where n is the length of the string s. The function f is called twice (once for "1" and once for "0"), and each call iterates through the entire string s once. Since we iterate through the string a constant number of times (2 times), the overall time complexity remains O(n).

The space complexity is O(1). The algorithm only uses a constant amount of extra space for variables cnt and mx within the helper function f, regardless of the input size. No additional data structures that scale with the input are created.

Learn more about how to find time and space complexity quickly.

Common Pitfalls

1. Incorrect Handling of Edge Cases with Empty Segments

A common mistake is not properly handling cases where the string contains only one type of character. Developers might incorrectly assume both characters will always be present in the string.

Pitfall Example:

# Incorrect approach that assumes both characters exist
def checkZeroOnes(self, s: str) -> bool:
    # This might fail if there are no '0's or no '1's
    ones_segments = s.split('0')  # Could result in ['111'] if no '0's
    zeros_segments = s.split('1')  # Could result in ['000'] if no '1's
  
    # Wrong: max() on empty filtered list will raise ValueError
    max_ones = max(len(seg) for seg in ones_segments if seg)
    max_zeros = max(len(seg) for seg in zeros_segments if seg)
    return max_ones > max_zeros

Solution: Handle empty cases explicitly by providing default values:

def checkZeroOnes(self, s: str) -> bool:
    ones_segments = [seg for seg in s.split('0') if seg]
    zeros_segments = [seg for seg in s.split('1') if seg]
  
    # Correctly handle empty lists with default value of 0
    max_ones = max((len(seg) for seg in ones_segments), default=0)
    max_zeros = max((len(seg) for seg in zeros_segments), default=0)
    return max_ones > max_zeros

2. Using Greater Than or Equal Instead of Strictly Greater

Developers often mistakenly use >= instead of > for the comparison, which would return incorrect results when both maximum lengths are equal.

Pitfall Example:

def checkZeroOnes(self, s: str) -> bool:
    # ... helper function code ...
  
    # Wrong: This returns True even when lengths are equal
    return find_max_consecutive_length("1") >= find_max_consecutive_length("0")

Solution: Always use strict comparison:

return find_max_consecutive_length("1") > find_max_consecutive_length("0")

3. Forgetting to Reset the Counter

A critical mistake is forgetting to reset the counter when encountering a different character, leading to incorrect cumulative counts.

Pitfall Example:

def find_max_consecutive_length(target_char: str) -> int:
    current_count = 0
    max_length = 0
  
    for char in s:
        if char == target_char:
            current_count += 1
            max_length = max(max_length, current_count)
        # Missing else block - counter never resets!
  
    return max_length

Solution: Always reset the counter when the sequence breaks:

def find_max_consecutive_length(target_char: str) -> int:
    current_count = 0
    max_length = 0
  
    for char in s:
        if char == target_char:
            current_count += 1
            max_length = max(max_length, current_count)
        else:
            current_count = 0  # Critical: Reset counter
  
    return max_length

4. Updating Maximum Only at the End of a Segment

Some developers try to update the maximum length only when a segment ends, which misses the last segment if the string ends with the target character.

Pitfall Example:

def find_max_consecutive_length(target_char: str) -> int:
    current_count = 0
    max_length = 0
  
    for i, char in enumerate(s):
        if char == target_char:
            current_count += 1
            # Wrong: Only updates when segment ends, misses last segment
            if i == len(s) - 1 or s[i + 1] != target_char:
                max_length = max(max_length, current_count)
        else:
            current_count = 0
  
    return max_length

Solution: Update the maximum whenever the count increases:

def find_max_consecutive_length(target_char: str) -> int:
    current_count = 0
    max_length = 0
  
    for char in s:
        if char == target_char:
            current_count += 1
            # Correct: Update maximum immediately
            max_length = max(max_length, current_count)
        else:
            current_count = 0
  
    return max_length
Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

Which of the following shows the order of node visit in a Breadth-first Search?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More