#1221

Split a String in Balanced Strings

Easy
StringGreedyCountingTwo PointersGreedy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach uses a single pass through the string while maintaining a balance counter. This allows us to efficiently count balanced substrings without checking every possible substring.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a balance counter and a result counter to zero.
  2. 2Step 2: Loop through each character in the string, adjusting the balance counter: +1 for 'L' and -1 for 'R'.
  3. 3Step 3: Whenever the balance counter reaches zero, increment the result counter.
solution.py8 lines
1def balanced_string_split(s):
2    balance = 0
3    count = 0
4    for char in s:
5        balance += 1 if char == 'L' else -1
6        if balance == 0:
7            count += 1
8    return count

Complexity note: The time complexity is O(n) since we only loop through the string once. The space complexity is O(1) because we use a fixed amount of extra space for the counters.

  • 1The balance counter effectively tracks the number of 'L' and 'R' characters.
  • 2Each time the balance returns to zero, it indicates a complete balanced substring.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.