We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Find the Longest Balanced Substring of a Binary String

Difficulty: Easy


Problem Description

You are given a binary string s consisting only of zeroes and ones. A substring of s is considered balanced if all zeroes are before ones and the number of zeroes is equal to the number of ones inside the substring. Notice that the empty substring is considered a balanced substring. Return the length of the longest balanced substring of s.

Key Insights

  • A balanced substring contains an equal number of '0's and '1's.
  • The '0's must precede the '1's in the balanced substring.
  • The maximum length of balanced substring can be computed by counting the number of paired '0's and '1's.
  • The search for balanced substrings can be optimized by scanning through the string and keeping track of counts.

Space and Time Complexity

Time Complexity: O(n)
Space Complexity: O(1)

Solution

To solve the problem, we can use a simple linear scan approach. We will iterate through the string while maintaining two counters: one for '0's and one for '1's. Whenever the counts of '0's and '1's match, we compute the length of the balanced substring formed and update the maximum length found. This approach ensures that we only traverse the string once, making it efficient.

Code Solutions

def longest_balanced_substring(s: str) -> int:
    zero_count = 0
    one_count = 0
    max_length = 0
    
    for char in s:
        if char == '0':
            zero_count += 1
        else:
            one_count += 1
        
        # Check if counts are equal
        if zero_count == one_count:
            max_length = max(max_length, zero_count + one_count)
    
    return max_length
← Back to All Questions