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
โš–๏ธ Balance Scale FactoryInput: R L R R L LR+1L-1R+1R+1L-1L-1Scale Balance Tracking:Counter: 1After RUnbalancedCounter: 0After Lโœ“ BALANCED!โš–๏ธCounter: 1After RUnbalancedCounter: 2After RUnbalancedCounter: 1After LUnbalancedCounter: 0After Lโœ“ BALANCED!โš–๏ธ๐Ÿญ Factory OutputCompleted 2 balance scales: [RL] [RRLL]Greedy cutting maximizes production efficiency!
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!
Asked in
Amazon 15 Google 12 Microsoft 8 Meta 6
58.8K Views
Medium Frequency
~5 min Avg. Time
2.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen