Split a String in Balanced Strings

EasyGreedygreedy

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

A string is **balanced** if it has the same number of 'L' and 'R' characters. You are given a balanced string s. Cut it into consecutive substrings so that every piece is balanced and non-empty, using as many pieces as possible. Return that maximum number of pieces.

Examples

Input: s = "RLRRLLRLRL"
Output: 4
`RL`, `RRLL`, `RL`, `RL` are all balanced.
Input: s = "RLRRRLLRLL"
Output: 2
`RL` and `RRRLLRLL` is the best possible split.
Input: s = "LLLLRRRR"
Output: 1
No proper prefix is balanced, so the string stays whole.

Constraints

  • 2 <= s.length <= 1000
  • `s[i]` is `'L'` or `'R'`
  • `s` is balanced

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More greedy problems