Minimum Remove to Make Valid Parentheses (LeetCode 1249): Solution and Explanation
You get a string of letters and parentheses. Delete the fewest parentheses so the rest is balanced, and return the result. Letters always stay.
Intuition
A bracket string is valid exactly when every ')' has an unmatched '(' somewhere to its left, and no '(' is left open at the end. So the only parentheses that must go are the ones that break one of those two rules.
The first rule is checked during a left-to-right scan. If a ')' shows up when no '(' is waiting, nothing in the rest of the string can fix it, because a partner would have to come before it. That ')' has to be removed.
The second rule is checked at the end. Any '(' that is still waiting after the whole string was read never got a ')', so it has to be removed too.
Both kinds of removal are forced: any valid answer must delete at least that many brackets. And deleting exactly those leaves a balanced string. So the scan removes the minimum. A stack of indices is the natural way to remember which '(' are still waiting and where they sit.
Approach: Stack of open indices
- Copy the string into a mutable array of characters and create an empty stack.
- Scan each index
i. Ifs[i]is '(', pushi. - If
s[i]is ')' and the stack is non-empty, pop: the '(' on top and this ')' form a pair that stays. - If
s[i]is ')' and the stack is empty, mark positionias removed. - After the scan, mark every index still on the stack as removed, then join the characters that were not marked.
Step-by-step example
s = "lee(t(c)o)de)"
- "lee" is letters, so all three stay and the stack is still empty.
- Index 3 is '(', push 3. Index 4 't' stays. Index 5 is '(', push 5. The stack is [3, 5].
- Index 6 'c' stays. Index 7 is ')', pop 5: positions 5 and 7 are a pair. The stack is [3].
- Index 8 'o' stays. Index 9 is ')', pop 3: positions 3 and 9 are a pair. The stack is empty.
- "de" stays. Index 12 is ')' and the stack is empty, so mark it removed.
- The scan ends with an empty stack, so no '(' needs removal. Joining the rest gives "lee(t(c)o)de" with one removal.
Code: Python, Java, C++
1class Solution:
2 def minRemoveToMakeValid(self, s: str) -> str:
3 chars = list(s)
4 stack = []
5 for i, ch in enumerate(chars):
6 if ch == '(':
7 stack.append(i)
8 elif ch == ')':
9 if stack:
10 stack.pop()
11 else:
12 chars[i] = ''
13 for i in stack:
14 chars[i] = ''
15 return ''.join(chars)1class Solution {
2 public String minRemoveToMakeValid(String s) {
3 StringBuilder sb = new StringBuilder(s);
4 Deque<Integer> stack = new ArrayDeque<>();
5 for (int i = 0; i < sb.length(); i++) {
6 char ch = sb.charAt(i);
7 if (ch == '(') {
8 stack.push(i);
9 } else if (ch == ')') {
10 if (!stack.isEmpty()) {
11 stack.pop();
12 } else {
13 sb.setCharAt(i, '*');
14 }
15 }
16 }
17 while (!stack.isEmpty()) {
18 sb.setCharAt(stack.pop(), '*');
19 }
20 return sb.toString().replace("*", "");
21 }
22}1class Solution {
2public:
3 string minRemoveToMakeValid(string s) {
4 vector<int> stack;
5 for (int i = 0; i < (int)s.size(); i++) {
6 if (s[i] == '(') {
7 stack.push_back(i);
8 } else if (s[i] == ')') {
9 if (!stack.empty()) {
10 stack.pop_back();
11 } else {
12 s[i] = '*';
13 }
14 }
15 }
16 for (int i : stack) s[i] = '*';
17 s.erase(remove(s.begin(), s.end(), '*'), s.end());
18 return s;
19 }
20};Time and space complexity
O(n)
Each character is visited once in the scan, each index is pushed and popped at most once, and the final join is another linear pass.
O(n)
The character array and, in the worst case (a string of only '('), the stack both hold n entries.
Other approaches
Two passes with a counter (time O(n), space O(n))
Scan left to right with an open counter and skip any ')' that would make it negative. Then scan the kept characters right to left and skip the extra '(' while counting closes. No stack of indices is needed, but the second pass removes the rightmost surplus '(' rather than the specific unmatched ones, which can give a different (still minimal) string.
Remove brackets and test (brute force) (time O(2^n · n), space O(n))
Try deleting 0, 1, 2, ... parentheses in every combination until a valid string appears. It proves the minimum directly but grows exponentially with the number of brackets.
Common mistakes
- Deleting characters from the string inside the loop. Each deletion shifts later indices and costs O(n), which makes the whole thing O(n²).
- Only counting brackets instead of remembering where the unmatched '(' are. A count tells you how many to remove at the end but not which ones.
- Removing the first surplus '(' instead of the ones still on the stack. An early '(' may already be matched with a later ')'.
- Forgetting the leftover step, which leaves strings like "(()" unbalanced.
Frequently asked questions
Why is the answer guaranteed to be minimal?
Every ')' removed during the scan had no '(' before it, and every '(' removed at the end had no ')' after it. Any valid result must drop those brackets, so no answer can remove fewer.
Is the output unique?
Not always. For "lee(t(c)o)de)" you could also remove a different ')' and still be valid with one deletion. LeetCode accepts any minimal answer; the stack scan always returns the one that drops the unmatched brackets it finds.
Can I do it without a stack?
Yes. A counter and two passes (left to right for extra ')', right to left for extra '(') work in O(n) as well. The stack version is easier to reason about because it names the exact unmatched positions.
Why store indices instead of the characters?
Every item on the stack is a '(', so the character itself carries no information. The index is what you need to mark the right position for removal later.