Minimum Remove to Make Valid Parentheses solution explained
Minimum Remove to Make Valid Parentheses asks you to delete as few brackets as possible from a string of letters and round brackets so the brackets balance, and return any one result. Scan once with a stack of indexes of open brackets: a closing bracket either matches the most recent open one or is marked for removal, and open brackets still on the stack at the end are marked too. Rebuilding the string without the marked positions gives an O(n) time, O(n) space answer.
By Evin JohnPublished 8 min read
The task, restated
You are given a string made of lowercase letters and the characters ( and ). Remove the smallest possible number of bracket characters so that what remains is balanced: every ( has a matching ) after it, and no ) appears without an earlier unmatched (. Letters are never removed. If several results remove the same minimum number of brackets, any one of them is accepted. An empty string and a string with no brackets are both already valid.
| Input | One valid output | Brackets removed |
|---|---|---|
| a)b(c)d | ab(c)d | 1, the stray ) at index 1 |
| ))(( | (empty string) | 4, nothing can be matched |
| (a(b) | a(b) or (ab) | 1, either open bracket can go |
| x(y)z) | x(y)z | 1 |
| ((a) | (a) | 1 |
| nobrackets | nobrackets | 0 |
The third row matters for testing: more than one answer is correct, so a test that compares your output with one fixed string will reject valid code. Check instead that the output is balanced, that it was produced only by deleting brackets, and that its length is the original length minus the minimum.
How it relates to Valid Parentheses
Valid Parentheses answers yes or no. This problem asks you to repair the string, which means you have to know which brackets were the problem, not just whether there was one. That is why the stack holds indexes rather than characters. Interviewers use it as the natural step up, and they often follow with:
- Return every minimal answer, not just one. That is a much harder problem; breadth-first search over removals, with pruning, is the usual route.
- Several bracket types, like ( [ {. The stack holds indexes, and a closing bracket only matches the same type on top.
- Count the removals only. No rebuild needed: the answer is the number of unmatched ) found during the scan plus the stack size at the end.
- Constant extra space apart from the output. Use two passes with a counter instead of a stack, shown below.
Brute force: breadth-first search over removals
Start with the original string. If it is balanced, you are done. Otherwise build every string with one bracket removed and check those; then every string with two removed, and so on. The first level that contains a balanced string tells you the minimum, and any balanced string on that level is an answer. The number of candidates grows exponentially with the number of brackets, so this only works for short inputs, but it is guaranteed minimal, which makes it the right oracle for testing.
def is_balanced(t):
depth = 0
for ch in t:
if ch == "(":
depth += 1
elif ch == ")":
depth -= 1
if depth < 0:
return False
return depth == 0
def min_remove_slow(s):
level = {s}
while True:
good = [t for t in level if is_balanced(t)]
if good:
return min(good)
level = {t[:i] + t[i + 1:] for t in level for i in range(len(t)) if t[i] in "()"}Optimal approach: mark with a stack, rebuild once
Scan left to right. Push the index of every ( onto a stack. When you meet a ), pop the most recent open index if there is one, since those two match. If the stack is empty, nothing can match this ), so mark its index for removal. After the scan, every index still on the stack is an ( with no partner, so mark those as well. Finally, build the output from the characters whose indexes are not marked. Each character is pushed, popped and copied at most once.
def min_remove(s):
drop = set()
open_at = []
for i, ch in enumerate(s):
if ch == "(":
open_at.append(i)
elif ch == ")":
if open_at:
open_at.pop()
else:
drop.add(i)
drop.update(open_at)
return "".join(ch for i, ch in enumerate(s) if i not in drop)function minRemove(s) {
const chars = s.split("");
const openAt = [];
for (let i = 0; i < chars.length; i++) {
if (chars[i] === "(") {
openAt.push(i);
} else if (chars[i] === ")") {
if (openAt.length > 0) openAt.pop();
else chars[i] = "";
}
}
for (const i of openAt) chars[i] = "";
return chars.join("");
}Why is this minimal? When a ) is marked during the scan, every ( before it is already paired, so the prefix up to that point holds more closing than opening brackets, and at least one ) in it has to go. Likewise, each ( left on the stack has no unmatched ) after it, so the suffix from it onward holds more opening than closing brackets. So any valid answer removes at least that many brackets, and this method removes exactly that many. Saying this in one or two sentences is what separates a remembered solution from an understood one.
Alternative: two passes with a counter
If the interviewer asks to avoid the stack, use a balance counter. In a left-to-right pass, skip any ) that would push the balance below zero and keep everything else. Whatever balance is left at the end is the number of surplus ( characters, and the safe ones to delete are the rightmost ones. So in a right-to-left pass over what you kept, skip that many ( and keep the rest. Apart from the output being built, the extra space is a single counter.
def min_remove_two_pass(s):
kept = []
balance = 0
for ch in s:
if ch == ")":
if balance == 0:
continue
balance -= 1
elif ch == "(":
balance += 1
kept.append(ch)
out = []
for ch in reversed(kept):
if ch == "(" and balance > 0:
balance -= 1
continue
out.append(ch)
return "".join(reversed(out))Trace: (a(b)
| Index | Character | Action | Stack of open indexes |
|---|---|---|---|
| 0 | ( | push 0 | [0] |
| 1 | a | letter | [0] |
| 2 | ( | push 2 | [0, 2] |
| 3 | b | letter | [0, 2] |
| 4 | ) | pop 2, matched | [0] |
| end | mark 0 for removal | [] |
The stack method returns a(b), keeping the inner pair. The two-pass method drops the rightmost surplus ( instead, so it returns (ab). Both remove one bracket and both are accepted, which is a good illustration of why tests should check properties rather than exact strings.
Time and space
| Approach | Time | Extra space |
|---|---|---|
| Breadth-first search over removals | Exponential in b | Exponential in b |
| Stack of indexes and a drop set | O(n) | O(n) |
| Two passes with a counter | O(n) | O(1) besides the output |
Edge cases
- An empty string, or one with no brackets, comes back unchanged.
- Only closing brackets: all are removed in the scan.
- Only opening brackets: all stay on the stack and are removed at the end.
- Already balanced input: nothing is marked, and the output equals the input.
- A long string such as 100,000 open brackets: both methods are linear and iterative, so there is no recursion depth problem.
Mistakes to avoid
- Removing characters from the string inside the loop, which shifts the indexes still on the stack and costs O(n) per removal.
- Pushing characters instead of indexes, so you know an ( is unmatched but not where it is.
- Forgetting the open brackets left on the stack after the scan.
- In the two-pass version, deleting the leftmost surplus ( instead of the rightmost, which can break pairs that were fine.
- Building the output with repeated string concatenation in a language where that copies every time.
How to explain it out loud
Fictional example
- Candidate
- I'll scan once with a stack of indexes of open brackets. A closing bracket pops a match if there is one, otherwise I mark it to delete.
- Candidate
- Whatever is left on the stack at the end are open brackets with no partner, so I mark those too, then rebuild the string without the marked positions.
- Candidate
- It's minimal because every marked bracket has no possible partner, so any valid answer has to drop at least those. Linear time and space, and if you want constant extra space I can do it in two passes with a counter.
Related problems
Valid Palindrome II is another string repair question, where you may delete at most one character to fix the string. Insert Delete GetRandom O(1) shares the habit of marking and patching rather than shifting elements. Basic Calculator and Decode String are the next bracket problems up in difficulty, where the stack saves state rather than positions.
Where Natively comes in
While you practice on a Mac or Windows PC, Natively can read a string problem like this one from a screenshot and write an approach and code, which helps when you want to compare the stack and two-pass versions side by side. It also keeps a transcript of your explanation, so you can check whether you stated why the answer is minimal. Details are on the AI interview assistant page.
Questions people ask
How do you solve Minimum Remove to Make Valid Parentheses?
Scan once with a stack of indexes of open brackets. A closing bracket pops a match if there is one, otherwise mark it for removal. Open brackets left on the stack at the end are marked too, then rebuild the string without the marked positions.
Why is the stack approach minimal?
Every marked bracket has no possible partner. A marked ) closes a prefix with more closing than opening brackets, and each leftover ( starts a suffix with more opening than closing brackets, so any valid answer must remove at least that many.
Can you solve it without a stack?
Yes, in two passes with a balance counter. Left to right, skip any ) that would push the balance below zero. Then, right to left, skip as many ( as the leftover balance. Apart from the output, the extra space is a single counter.
What is the time complexity of Minimum Remove to Make Valid Parentheses?
O(n) time for both the stack method and the two-pass counter. The stack method uses O(n) extra space and the counter version O(1) besides the output, while breadth-first search over removals is exponential.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
