[LeetCode] Remove K-Balanced Substrings

3703. Remove K-Balanced Substrings

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
string removeSubstring(string s, int k) {
vector<int> A;
for(auto& ch : s) {
if(ch == '(') {
if(A.size() == 0 or A.back() < 0) A.push_back(1);
else A.back()++;
} else {
if(A.size() == 0 or A.back() > 0) A.push_back(-1);
else A.back()--;
}
if(A.size() >= 2 and A.back() == -k and A[A.size()-2] >= k) {
A.pop_back();
A.back() -= k;
if(A.back() == 0) A.pop_back();
}
}
string res = "";
for(auto& cnt : A) res += string(abs(cnt), cnt < 0 ? ')' : '(');
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/10/12/PS/LeetCode/remove-k-balanced-substrings/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.