Find the Longest Balanced Substring of a Binary String - Problem
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
- The number of zeroes is equal to the number of ones
Notice that the empty substring is considered a balanced substring.
Return the length of the longest balanced substring of s.
A substring is a contiguous sequence of characters within a string.
Input & Output
Example 1 — Basic Pattern
$
Input:
s = "01000111"
›
Output:
6
💡 Note:
The longest balanced substring is "000111" with 3 zeros followed by 3 ones, giving length 6
Example 2 — Multiple Patterns
$
Input:
s = "00111"
›
Output:
4
💡 Note:
We have 2 zeros and 3 ones in pattern. The longest balanced part is "0011" with length 4
Example 3 — No Valid Pattern
$
Input:
s = "111"
›
Output:
0
💡 Note:
No zeros present, so no balanced substring is possible
Constraints
- 1 ≤ s.length ≤ 50
- s consists only of '0' and '1'
Visualization
Tap to expand
Understanding the Visualization
1
Input
Binary string with mixed 0s and 1s
2
Find Pattern
Locate substrings where zeros appear before ones
3
Output
Length of longest balanced substring
Key Takeaway
🎯 Key Insight: Look for consecutive patterns of zeros followed by ones, then take the minimum count times 2
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code