Left Right Balance

Start Timer

0:00:00

Upvote
0
Downvote
Save question
Mark as completed
View comments (1)

You are working as a Data Analyst at Sigma Operations. The system continuously logs operational actions as a sequence of characters:

  • 'L' represents a left-side operation
  • 'R' represents a right-side operation

For monitoring system health and detecting anomalies, the platform defines a balanced action sequence as any contiguous segment of actions that contains an equal number of ‘L’ and ‘R’ events.

Write a Python function that takes a string s and returns the maximum number of balanced substrings that can be obtained by splitting the string.

Rules :

  1. Full Partitioning: Every character in the original string s must be included in one of the resulting substrings.
  2. Uniform Balance: Every individual substring resulting from the split must be balanced (Count of ‘L’ == Count of ‘R’).
  3. Order Preservation: The original sequence of events must be maintained.
  4. Maximization: You must split the string into as many pieces as possible.
  5. Validation: If the string cannot be fully partitioned into balanced parts (e.g., "LLR"), the output should be 0.

Constraints

  • 1 ≤ len(s) ≤ 10^5
  • s contains only 'L' and 'R'

Example 1:

Input

s = "RLRRLLRLRL"

Output

4

Explanation:

This segmentation gives maximum number of balanced substrings, hence the output is 4.

"RL" | "RRLL" | "RL" | "RL"

Example 2:

Input

s = "LLR"

Output

0

Explanation:

No valid split exists because the entire string cannot be partitioned into segments that are all balanced, hence the output is 0.

.
.
.
.
.


Comments

Loading comments