Remove K-Balanced Substrings Problem
Description
LeetCode Problem 3703.
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 <= 10^5sconsists only of'('and')'.1 <= k <= s.length / 2
Solution
Approach: 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 equalsk, and the count of the previous element is greater than or equal tok, then pop the top element and subtractkfrom 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.
Complexity: The time complexity is O(n), and the space complexity is O(n), where n is the length of string s.
class Solution:
def removeSubstring(self, s: str, k: int) -> str:
stk = []
for c in s:
if stk and stk[-1][0] == c:
stk[-1][1] += 1
else:
stk.append([c, 1])
if c == ")" and len(stk) > 1 and stk[-1][1] == k and stk[-2][1] >= k:
stk.pop()
stk[-1][1] -= k
if stk[-1][1] == 0:
stk.pop()
return "".join(c * v for c, v in stk)