Left Right Balance
Start Timer
0:00:00
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 :
- Full Partitioning: Every character in the original string
smust be included in one of the resulting substrings. - Uniform Balance: Every individual substring resulting from the split must be balanced (Count of ‘L’ == Count of ‘R’).
- Order Preservation: The original sequence of events must be maintained.
- Maximization: You must split the string into as many pieces as possible.
- Validation: If the string cannot be fully partitioned into balanced parts (e.g.,
"LLR"), the output should be0.
Constraints
1 ≤ len(s) ≤ 10^5scontains 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