Split a String in Balanced Strings — LeetCode 1221 Python Solution
- Problem
- #1221
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- s = "RLRRLLRLRL"
- Output
- 4
- Explanation
- s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'.
Python solution
class Solution:
def balancedStringSplit(self, s: str) -> int:
ans = l = 0
for c in s:
if c == 'L':
l += 1
else:
l -= 1
if l == 0:
ans += 1
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 1221. Split a String in Balanced Strings is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1221. Split a String in Balanced Strings?
- LeetCode 1221. Split a String in Balanced Strings is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1221. Split a String in Balanced Strings?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1221. Split a String in Balanced Strings?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1221. Split a String in Balanced Strings cover?
- LeetCode 1221. Split a String in Balanced Strings is tagged Greedy, String and Counting on LeetCode.