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.
We use a stack to maintain the current state of the string. Each element in the stack is a pair representing a character and its consecutive count.
Traverse each character in the string:
')', and there are at least two elements in the stack, and the count of the top element equals k, and the count of the previous element is greater than or equal to k, then pop the top element and subtract k from the count of the previous element. If the count of the previous element becomes 0, pop it as well.After traversal, the remaining elements in the stack represent the final state of the string. We concatenate these elements in order to get the result string.
The time complexity is O(n) and the space complexity is O(n), where n is the length of string s.
| 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 |
Remove K-Balanced Substrings | LeetCode 3703 | Most Optimal Solution • Sanyam IIT Guwahati • 1,920 views views
Watch 7 more video solutions →Practice Remove K-Balanced Substrings with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor