Maximum Number of Balanced L/R Pieces

Quick Overview

Maximum Number of Balanced L/R Pieces. The string s has equally many L and R characters. Partition the entire string into nonempty contiguous pieces, each also containing equal counts of L and R.

Maximum Number of Balanced L/R Pieces

Company: Infosys

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

### Problem The string s has equally many L and R characters. Partition the entire string into nonempty contiguous pieces, each also containing equal counts of L and R. Return the maximum possible number of pieces. ```cpp class Solution { public: int balancedStringSplit(string s); }; ``` ### Examples **Example 1:** ```text Input: s = "LRLRLR" Output: 3 Explanation: The three pieces LR,LR,LR are balanced and no balanced nonempty piece can be shorter than2. ``` **Example 2:** ```text Input: s = "LLRR" Output: 1 Explanation: No proper prefix is balanced, so the whole string is the only possible first piece. ``` ### Constraints - The string has length 2 to 1000. - Every character is L or R. - The full string has equal counts of L and R. ### Contract considerations Pieces are contiguous and cover all characters. The input itself is balanced. ```hint Read the boundary condition May a piece contain an R before an L, and must every character belong to a nonempty piece? ``` ### Boundary reminders Pieces are contiguous and cover all characters. The input itself is balanced.

Overview: Maximum Number of Balanced L/R Pieces. The string s has equally many L and R characters. Partition the entire string into nonempty contiguous pieces, each also containing equal counts of L and R.

Infosys logo
Infosys
Source window: 0–3 months · as of Oct 21, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

Problem

The string s has equally many L and R characters. Partition the entire string into nonempty contiguous pieces, each also containing equal counts of L and R. Return the maximum possible number of pieces.

class Solution {
public:
    int balancedStringSplit(string s);
};

Examples

Example 1:

Input: s = "LRLRLR"
Output: 3
Explanation: The three pieces LR,LR,LR are balanced and no balanced nonempty piece can be shorter than2.

Example 2:

Input: s = "LLRR"
Output: 1
Explanation: No proper prefix is balanced, so the whole string is the only possible first piece.

Constraints

  • The string has length 2 to 1000.
  • Every character is L or R.
  • The full string has equal counts of L and R.

Contract considerations

Pieces are contiguous and cover all characters. The input itself is balanced.

Boundary reminders

Pieces are contiguous and cover all characters. The input itself is balanced.