Split a String in Balanced Strings - Problem
Balanced strings are those that have an equal quantity of 'L' and 'R' characters.
Given a balanced string s, split it into some number of substrings such that:
- Each substring is balanced.
Return the maximum number of balanced strings you can obtain.
Input & Output
Example 1 — Basic Case
$
Input:
s = "RLRRLLRLRL"
›
Output:
4
💡 Note:
We can split into "RL", "RRLL", "RL", "RL", each substring has equal number of 'R' and 'L' characters. Maximum possible splits = 4.
Example 2 — Minimum Size
$
Input:
s = "RLRL"
›
Output:
2
💡 Note:
We can split into "RL", "RL". Each has 1 'R' and 1 'L', so 2 balanced substrings.
Example 3 — All Together
$
Input:
s = "LLLLRRRR"
›
Output:
1
💡 Note:
The entire string is balanced (4 L's and 4 R's), but any proper substring would be unbalanced. So maximum splits = 1.
Constraints
- 2 ≤ s.length ≤ 1000
- s[i] is either 'L' or 'R'
- s is a balanced string
Visualization
Tap to expand
Understanding the Visualization
1
Input
Balanced string with equal L and R characters
2
Process
Track balance counter, split when it reaches zero
3
Output
Maximum number of balanced substrings possible
Key Takeaway
🎯 Key Insight: Greedily split whenever the running balance counter returns to zero
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code