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
Split Balanced Strings: "RLRRLLRLRL"Input StringRLRRLLRLRLGreedy Split Points (Balance = 0)RLRRLLRLRL4 Balanced SubstringsAlgorithm: Track balance (+1 for R, -1 for L)Split whenever balance reaches 0 (found balanced substring)Output: 4 (maximum possible splits)Time: O(n), Space: O(1) - Optimal greedy solution
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
Asked in
Google 15 Microsoft 12 Amazon 8
113.6K Views
Medium Frequency
~8 min Avg. Time
2.8K 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