Split a String in Balanced Strings (LeetCode 1221): Solution and Explanation
You get a string of L and R characters with equal counts of each. Cut it into the largest number of pieces that each have equal L and R counts.
Intuition
Think of R as a step up and L as a step down. A piece is balanced exactly when it ends at the same height it started.
Walk the string from the left and track the height, the running balance. Each time it returns to 0, everything since the last cut is a balanced piece.
Cut there immediately. Waiting for a later zero would only glue two balanced pieces together, and the rest of the string stays balanced either way. So the answer is the number of times the balance touches 0.
Approach: Greedy cut at every zero balance
- Set
balance = 0andcount = 0. - For each character, add 1 for
'R'and subtract 1 for'L'. - Whenever
balancebecomes 0, the current piece is balanced: incrementcount. - Return
count.
Step-by-step example
s = "RLRRLLRLRL"
- R makes the balance 1, L brings it back to 0: cut "RL", count = 1.
- R, R raise the balance to 2; L, L bring it to 0: cut "RRLL", count = 2.
- R then L returns to 0: cut "RL", count = 3.
- R then L returns to 0 once more: cut "RL", count = 4. Return 4.
Code: Python, Java, C++
1class Solution:
2 def balancedStringSplit(self, s: str) -> int:
3 balance = 0
4 count = 0
5 for ch in s:
6 balance += 1 if ch == 'R' else -1
7 if balance == 0:
8 count += 1
9 return count1class Solution {
2 public int balancedStringSplit(String s) {
3 int balance = 0;
4 int count = 0;
5 for (char ch : s.toCharArray()) {
6 balance += ch == 'R' ? 1 : -1;
7 if (balance == 0) {
8 count++;
9 }
10 }
11 return count;
12 }
13}1class Solution {
2public:
3 int balancedStringSplit(string s) {
4 int balance = 0;
5 int count = 0;
6 for (char ch : s) {
7 balance += ch == 'R' ? 1 : -1;
8 if (balance == 0) {
9 count++;
10 }
11 }
12 return count;
13 }
14};Time and space complexity
O(n)
Each character is read once.
O(1)
Only the balance and the count are stored.
Other approaches
Two counters (time O(n), space O(1))
Keep separate counts of L and R and cut whenever they are equal. It is the same algorithm with balance = R count - L count.
Stack of unmatched characters (time O(n), space O(n))
Push a character when it matches the top or the stack is empty, pop when it is the opposite, and count each time the stack empties. It works but stores up to n characters for no gain.
Common mistakes
- Only counting cuts when the balance returns to 0 from above. A piece like "LLRR" dips below zero first and is just as balanced.
- Resetting the balance to 0 after a cut. It is already 0 at that point, but resetting on any other condition breaks the count.
- Trying to split into the smallest pieces like "RL" only. Pieces such as "RRLL" cannot be split further, so the count must come from the zero crossings.
Frequently asked questions
Why is cutting as early as possible optimal?
If a prefix is balanced, the remaining suffix is also balanced because the whole string is. Cutting the prefix off never prevents any split of the suffix, so taking the earliest cut can only add pieces.
Can the balance go negative?
Yes. A piece that starts with L dips below zero before coming back. The check is only whether the balance equals 0, not its sign.
Is the answer always at least 1?
Yes. The input is guaranteed balanced, so the balance is 0 after the last character and the whole string counts as one piece at minimum.