Find the Longest Balanced Substring of a Binary String - Problem
You are given a binary string s consisting only of '0's and '1's.
A substring of s is considered balanced if:
- All zeroes appear before all ones
- The number of zeroes equals the number of ones
For example, "0011" is balanced (2 zeros, 2 ones, zeros first), but "0101" is not (zeros and ones are mixed).
Note: The empty substring is considered balanced.
Goal: Return the length of the longest balanced substring.
Example: In s = "01000111", the longest balanced substring is "000111" with length 6.
Input & Output
example_1.py β Basic Case
$
Input:
s = "01000111"
βΊ
Output:
6
π‘ Note:
The longest balanced substring is "000111" (positions 2-7). It has 3 zeros followed by 3 ones, making it perfectly balanced with length 6.
example_2.py β Mixed Pattern
$
Input:
s = "00111"
βΊ
Output:
4
π‘ Note:
The longest balanced substring is "0011" (positions 0-3). We have 2 zeros followed by 2 ones, giving us length 4. The remaining "1" cannot form a balanced substring.
example_3.py β No Balance Possible
$
Input:
s = "111"
βΊ
Output:
0
π‘ Note:
There are no zeros in the string, so no balanced substring is possible. The only balanced substring is the empty string with length 0.
Constraints
- 1 β€ s.length β€ 50
-
s[i] is either
'0'or'1' - The string consists only of binary characters
Visualization
Tap to expand
Understanding the Visualization
1
Count Leaders
Count consecutive leaders (0s) that are available for partnership
2
Match Followers
As followers (1s) arrive, pair them with available leaders
3
Record Formation
When we have a perfect match, record the formation size
4
Reset on Disruption
If a new leader arrives after followers, start a new formation
Key Takeaway
π― Key Insight: Use a single pass with smart counter management - track available leaders and match them with followers, resetting when the dance formation pattern breaks.
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code