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 a String in Balanced Strings INPUT String s = "RLRRLLRLRL" R L R R L L R L R L Index: 0 1 2 3 4 5 6 7 8 9 R = Right L = Left Balanced = equal R and L Find max balanced splits Length: 10 chars 5 R's and 5 L's ALGORITHM STEPS 1 Initialize count=0, result=0 2 Iterate String For each character 3 Update Counter R: count++, L: count-- 4 Check Balance If count==0: result++ Execution Trace i=0: R cnt=1 i=1: L cnt=0 [OK] i=2: R cnt=1 i=3: R cnt=2 i=4: L cnt=1 i=5: L cnt=0 [OK] i=6: R cnt=1 i=7: L cnt=0 [OK] i=8: R cnt=1 i=9: L cnt=0 [OK] FINAL RESULT 4 Balanced Substrings Found: RL Split 1 RRLL Split 2 RL Split 3 RL Split 4 Original with splits: RL|RRLL|RL|RL Each split is balanced: RL: 1R, 1L [OK] RRLL: 2R, 2L [OK] RL: 1R, 1L [OK] RL: 1R, 1L [OK] Output: 4 Key Insight: Use a greedy counter approach: increment for 'R', decrement for 'L'. When counter reaches 0, we found a balanced substring. This greedy split maximizes the number of balanced parts. TutorialsPoint - Split a String in Balanced Strings | Greedy Counter Approach
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