Leetcode 2609: Find the Longest Balanced Substring of a Binary String

grid47
grid47
Exploring patterns and algorithms
Feb 20, 2024 5 min read

You are given a binary string consisting of only ‘0’s and ‘1’s. A substring of this binary string is considered balanced if it contains equal numbers of ‘0’s and ‘1’s, and all the ‘0’s come before the ‘1’s. Your task is to find the length of the longest balanced substring.
Problem
Approach
Steps
Complexity
Input: You are given a binary string s. The string consists only of '0's and '1's.
Example: s = "11010010"
Constraints:
• 1 <= s.length <= 50
• s consists only of '0' and '1'.
Output: Return the length of the longest balanced substring. A balanced substring is one where the count of '0's equals the count of '1's, and all '0's come before the '1's.
Example: Output: 4
Constraints:
• The output is a single integer representing the length of the longest balanced substring.
Goal: To find the longest balanced substring where the number of '0's equals the number of '1's and '0's come before '1's.
Steps:
• Initialize counters for '0's and '1's as you traverse the string.
• If a '0' is encountered, increase the '0' counter, and reset the '1' counter.
• If a '1' is encountered, check if it can balance the '0's in the substring. If so, update the answer with the longest balanced substring length found.
Goal: Ensure that the solution handles edge cases like empty substrings and different string lengths.
Steps:
• The input string length will be between 1 and 50.
Assumptions:
• The string contains only '0' and '1'.
Input: s = "01000111"
Explanation: In this case, the longest balanced substring is '000111' which has length 6. It contains 3 '0's followed by 3 '1's.

Input: s = "00111"
Explanation: The longest balanced substring is '0011', which has length 4, with 2 '0's followed by 2 '1's.

Input: s = "111"
Explanation: There is no balanced substring except for the empty one, so the output is 0.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus