3703. Remove K-Balanced Substrings
Description
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 <= 105
s
consists only of'('
and')'
.1 <= k <= s.length / 2
Solutions
Solution 1: Stack
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:
- If the stack is not empty and the character of the top element matches the current character, increment the count of the top element.
- Otherwise, push the current character with count 1 as a new element onto the stack.
- If the current character is
')'
, 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\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
|