Watch 8 video solutions for Remove K-Balanced Substrings, a medium level problem involving String, Stack, Simulation. This walkthrough by Sanyam IIT Guwahati has 1,920 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.
You are given a string s consisting of '(' and ')', and an integer k.
A string is k-balanced if it is exactly k consecutive '(' followed by k consecutive ')', i.e., '(' * k + ')' * k.
For example, if k = 3, k-balanced is "((()))".
You must repeatedly remove all non-overlapping k-balanced substrings from s, and then join the remaining parts. Continue this process until no k-balanced substring exists.
Return the final string after all possible removals.
Example 1:
Input: s = "(())", k = 1
Output: ""
Explanation:
k-balanced substring is "()"
| Step | Current s |
k-balanced |
Result s |
|---|---|---|---|
| 1 | (()) |
( |
() |
| 2 | () |
() |
Empty |
Thus, the final string is "".
Example 2:
Input: s = "(()(", k = 1
Output: "(("
Explanation:
k-balanced substring is "()"
| Step | Current s |
k-balanced |
Result s |
|---|---|---|---|
| 1 | (()( |
( |
(( |
| 2 | (( |
- | (( |
Thus, the final string is "((".
Example 3:
Input: s = "((()))()()()", k = 3
Output: "()()()"
Explanation:
k-balanced substring is "((()))"
| Step | Current s |
k-balanced |
Result s |
|---|---|---|---|
| 1 | ((()))()()() |
|
()()() |
| 2 | ()()() |
- | ()()() |
Thus, the final string is "()()()".
Constraints:
2 <= s.length <= 105s consists only of '(' and ')'.1 <= k <= s.length / 2Problem Overview: You are given a string and an integer k. The task is to repeatedly remove substrings that are k-balanced until no more such substrings exist. After each removal, the remaining parts of the string join together, which may create new k-balanced segments. The goal is to simulate this process efficiently and return the final string.
Approach 1: Brute Force Simulation (O(n^2) time, O(n) space)
The most direct strategy repeatedly scans the string to detect substrings that satisfy the k-balanced condition. Once a valid segment is found, remove it and restart scanning because the merge may create new removable substrings. Implementation usually builds new strings or uses substring operations. The major cost comes from repeated rescans and string reconstruction, leading to O(n^2) time in the worst case and O(n) auxiliary space. This approach works for small inputs but quickly becomes too slow for interview constraints.
Approach 2: Stack-Based Simulation (O(n) time, O(n) space)
A more efficient strategy uses a stack to simulate the removals while scanning the string once. Push characters onto the stack and track the frequency balance of the current segment. Whenever the top portion of the stack forms a k-balanced substring, pop those characters immediately. This mirrors the effect of removing the substring and letting the remaining characters connect. Because each character is pushed and popped at most once, the total work is linear. The stack naturally models the dynamic merging behavior without repeatedly rebuilding strings.
The key insight is that substring removal problems often behave like bracket cancellation. By storing partial results in a stack, you only examine newly formed boundaries when characters are added or removed. This makes the algorithm a classic simulation problem combined with stack operations on a string.
Recommended for interviews: The stack-based solution is the expected approach. Interviewers want to see that you recognize the repeated-removal pattern and avoid rebuilding the string after every deletion. Explaining the brute force approach first shows understanding of the process, while transitioning to a stack demonstrates the optimization that reduces the complexity to linear time.
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Simulation | O(n^2) | O(n) | Useful for understanding the removal process or when input size is small |
| Stack-Based Simulation | O(n) | O(n) | Optimal approach for interviews and large inputs |