Split a String in Balanced Strings - Problem
Imagine you're tasked with organizing a sequence of left and right movements into balanced groups. A balanced string contains an equal number of 'L' (left) and 'R' (right) characters.
Given a balanced string s, your goal is to split it into the maximum number of balanced substrings. Each substring must be balanced on its own, meaning it has equal counts of 'L' and 'R' characters.
Example: For string "RLRRLLRLRL", you could split it as ["RL", "RRLL", "RL", "RL"] to get 4 balanced substrings, which is the maximum possible.
The key insight is to be greedy: whenever you find the first balanced substring, cut it immediately to maximize the total count!
Input & Output
example_1.py โ Basic Case
$
Input:
s = "RLRRLLRLRL"
โบ
Output:
4
๐ก Note:
We can split into ["RL", "RRLL", "RL", "RL"] - each part is balanced and we get maximum 4 substrings
example_2.py โ Longer Balanced Groups
$
Input:
s = "RLLLLRRRLR"
โบ
Output:
3
๐ก Note:
We can split into ["RLLLLRRR", "L", "R"] - wait, that's wrong. Actually ["RLLLLLRRR"] would be unbalanced. Correct split: ["RL", "LL", "RRR"] - no wait, that's also wrong. Let me recalculate: split as ["RLLLLRRR", "LR"] gives us 2 balanced substrings. Actually: ["RLLL", "LRRR", "LR"] - no. Correct answer: we get splits at positions where counter=0, giving us 3 total balanced substrings.
example_3.py โ Minimum Case
$
Input:
s = "RL"
โบ
Output:
1
๐ก Note:
The entire string "RL" is already balanced, so we get 1 balanced substring
Constraints
- 1 โค s.length โค 1000
- s[i] is either 'L' or 'R'
- s is guaranteed to be balanced (equal number of L and R)
Visualization
Tap to expand
Understanding the Visualization
1
Start with Empty Scale
Begin with counter = 0 (balanced scale)
2
Add Weights
R adds +1 to right side, L adds +1 to left side (net -1)
3
Detect Balance
When counter returns to 0, the scale is balanced again
4
Complete Scale
Count this balanced scale and start a new one immediately
5
Maximize Output
This greedy approach gives maximum number of complete scales
Key Takeaway
๐ฏ Key Insight: Cut immediately when balanced (counter = 0) to maximize total output. Waiting longer never increases the final count!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code