Similar Problems

Similar Problems not available

Find The Longest Balanced Substring Of A Binary String - Leetcode Solution

Companies:

LeetCode:  Find The Longest Balanced Substring Of A Binary String Leetcode Solution

Difficulty: Easy

Topics: string  

Problem Statement:

Given a binary string s, find the length of the longest balanced (well-formed) substring of s.

A balanced substring is a substring where the number of 0s and 1s are equal.

Example 1:

Input: "1101" Output: 4 Explanation: The longest balanced substring is "1101", which has 2 0s and 2 1s.

Example 2:

Input: "111000" Output: 6 Explanation: The longest balanced substring is "111000", which has 3 0s and 3 1s.

Approach:

We can solve this problem using a stack. We will iterate over the binary string s and push the index of the character onto the stack if it is 0 and pop the index from the stack if it is 1. For every pair of matching indices that we pop, we calculate the length of the balanced substring and update the maximum length.

Algorithm:

  1. Initialize a stack and a variable maxLen to 0.
  2. Iterate over the binary string s and for each character, do the following: a. If the character is 0, push its index onto the stack. b. If the character is 1, pop the top index from the stack.
    • If the stack is empty, this means the substring up to the current index is not balanced. In this case, push the index of the current character onto the stack.
    • If the stack is not empty, calculate the length of the balanced substring as the difference between the current index and the index on top of the stack. Update maxLen if this length is greater than maxLen.
  3. Return maxLen.

Time Complexity:

The algorithm has a time complexity of O(n) where n is the length of the binary string s.

Space Complexity:

The algorithm has a space complexity of O(n) where n is the length of the binary string s (for the stack).

Solution (Python):

class Solution: def findMaxBalancedSubstring(self, s: str) -> int: stack = [] maxLen = 0

    for i in range(len(s)):
        if s[i] == '0':
            stack.append(i)
        else:
            if stack:
                start = stack.pop()
                balancedLen = i - start
                maxLen = max(maxLen, balancedLen)
            else:
                stack.append(i)
                
    return maxLen

Test the solution with examples from the problem statement

sol = Solution() print(sol.findMaxBalancedSubstring("1101")) # Output: 4 print(sol.findMaxBalancedSubstring("111000")) # Output: 6

Find The Longest Balanced Substring Of A Binary String Solution Code

1