#3703
Remove K-Balanced Substrings
MediumStringStackSimulationStackGreedy
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using a stack to track the balance of parentheses allows us to efficiently identify and remove k-balanced substrings in a single pass.
⚙️
Algorithm
3 steps- 1Step 1: Use a stack to track counts of '(' and ')' and identify k-balanced sections.
- 2Step 2: For every k pairs found, mark them for removal.
- 3Step 3: Construct the final string excluding the marked sections.
solution.py7 lines
1def removeKbalanced(s, k):
2 stack = []
3 for char in s:
4 if char == '(': stack.append(1)
5 elif char == ')' and len(stack) >= k:
6 for _ in range(k): stack.pop()
7 return ''.join(['(' * len(stack) + ')' * len(stack)])ℹ
Complexity note: The linear time complexity comes from a single traversal of the string, while space is used to store the balance in the stack.
- 1Using a stack helps manage nested structures efficiently.
- 2Identifying patterns of parentheses allows for targeted removals.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.