Minimum Remove to Make Valid Parentheses
Medium
Topics
Given a string s of lowercase letters and the characters ( and ), remove the minimum number of parentheses so that the result is valid, and return it.
A string is valid when it is empty, or consists of letters only, or is a concatenation of valid strings, or is a valid string wrapped in one matching pair.
LeetCode notes that several answers may exist. That is true of which positions are removed — for "(()" either opening bracket can go — but both choices leave the same string, "()", and that is what is compared. So the answer here is unique and no tie-break is needed.
Example 1
lee(t(c)o)de. Letters are never removed.Input: s = "lee(t(c)o)de)" Output: "lee(t(c)o)de" Explanation: The final close bracket has nothing to match, so it goes. The other brackets already pair up.
Example 2
Input: s = "a)b(c)d" Output: "ab(c)d" Explanation: The close bracket at index 1 arrives before any open bracket.
Example 3
Input: s = "))(("
Output: ""
Explanation: Not one bracket can be matched, so all four are removed and only the empty string is left.
Constraints
- 1 <= s.length <= 10^5
- s[i] is either a lowercase English letter, ( or )
Editorial — intuition, approach, complexity and pitfalls
Intuition
A bracket needs removing exactly when it cannot be matched, and the two directions fail for different reasons. A ) is doomed the moment it appears with no unmatched ( before it — nothing later can rescue it. A ( is only doomed once the string ends with no ) left to close it, which is not knowable until the end.
So the close brackets can be judged on the spot during a left-to-right scan, while the open brackets have to be held as candidates and judged afterwards. Whatever is still being held when the scan finishes is unmatched and goes.
Minimality follows because nothing is removed unless it is unmatchable, and an unmatchable bracket has to be removed in any valid result. The count is therefore forced, and so is the resulting string.
Approach
- Scan left to right, keeping the indices of unmatched
(on a stack and a set of indices to delete. - On a
(, push its index. - On a
), pop a matching index if the stack has one; if it is empty, mark this index for deletion. - When the scan ends, mark every index still on the stack for deletion — those opens were never closed.
- Rebuild the string, skipping the marked indices. Letters are never touched.
Walkthrough
s = "lee(t(c)o)de)"
0123456789...
index char action stack delete
3 ( push 3 [3]
5 ( push 5 [3,5]
7 ) pop 5, matched [3]
9 ) pop 3, matched []
12 ) stack empty -> delete 12 [] {12}
nothing left on the stack, so no opens to remove
result: drop index 12 -> "lee(t(c)o)de"
---
s = "))(("
0 ) empty -> delete 0
1 ) empty -> delete 1
2 ( push 2
3 ( push 3
end: 2 and 3 never closed -> delete both
every character removed -> ""Complexity
- Time — O(n): one scan to decide and one to rebuild.
- Space — O(n): the stack and the delete set, both at most one entry per character.
Common Pitfalls
- Removing a
)on sight whenever the running balance is negative but forgetting the leftover(at the end."(a"needs its bracket removed too. - Counting unmatched brackets and then deleting that many from the wrong end. It matters which ones go — in example 2 the doomed bracket is at index 1, not the last one.
- Removing letters. Only parentheses are ever deleted.
- Rebuilding with repeated string concatenation inside the loop, which turns a linear scan quadratic in languages with immutable strings.
Full Solution — all languages
class Solution:
def minRemoveToMakeValid(self, s):
remove = set()
stack = []
for i, c in enumerate(s):
if c == "(":
stack.append(i)
elif c == ")":
if stack:
stack.pop()
else:
remove.add(i)
remove.update(stack)
return "".join(c for i, c in enumerate(s) if i not in remove)import java.util.*;
class Solution {
public String minRemoveToMakeValid(String s) {
boolean[] remove = new boolean[s.length()];
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(') stack.push(i);
else if (c == ')') {
if (!stack.isEmpty()) stack.pop();
else remove[i] = true;
}
}
for (int i : stack) remove[i] = true;
StringBuilder out = new StringBuilder();
for (int i = 0; i < s.length(); i++) if (!remove[i]) out.append(s.charAt(i));
return out.toString();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string minRemoveToMakeValid(string s) {
vector<char> remove(s.size(), 0);
vector<int> stack;
for (size_t i = 0; i < s.size(); i++) {
if (s[i] == '(') stack.push_back((int)i);
else if (s[i] == ')') {
if (!stack.empty()) stack.pop_back();
else remove[i] = 1;
}
}
for (int i : stack) remove[i] = 1;
string out;
for (size_t i = 0; i < s.size(); i++) if (!remove[i]) out += s[i];
return out;
}
};/**
* @param {string} s
* @return {string}
*/ var minRemoveToMakeValid = function(s) {
const remove = new Set();
const stack = [];
for (let i = 0; i < s.length; i++) {
if (s[i] === "(") stack.push(i);
else if (s[i] === ")") {
if (stack.length) stack.pop();
else remove.add(i);
}
}
for (const i of stack) remove.add(i);
let out = "";
for (let i = 0; i < s.length; i++) if (!remove.has(i)) out += s[i];
return out;
};