Minimum Add to Make Parentheses Valid
Minimum Add to Make Parentheses Valid is a medium stack problem solved with the stack basics pattern.
The best approach, optimal (two counters), runs in O(n) time and O(1) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (keep erasing matched pairs) up.
Problem
A string of brackets is valid when it is empty, or when it can be written as AB (two valid strings side by side), or as (A) (a valid string wrapped in one pair). Put simply: every ) closes an earlier ( that is still open, and no ( is left open at the end.
You are given a string s made only of '(' and ')'. In one move you may insert a single '(' or ')' at any position in the string.
Return the fewest insertions needed to make s valid.
Examples
Example 1
- Input
s = "())"- Output
1- Why
- The first two characters already form a pair. The last ')' has nothing to close, so one '(' must be inserted before it.
Example 2
- Input
s = "((("- Output
3- Why
- All three '(' stay open to the end. Each one needs its own ')' added after it.
Example 3
- Input
s = "()))(("- Output
4- Why
- The first pair is fine. The next two ')' close nothing (two insertions of '('), and the last two '(' are never closed (two insertions of ')').
Constraints
1 <= s.length <= 1000s[i]is'('or')'.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 13 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (keep erasing matched pairs) | O(n²) | O(n) |
| Stack of unmatched brackets | O(n) | O(n) |
| Optimal (two counters) | O(n) | O(1) |
1Brute force (keep erasing matched pairs)
O(n²)Each pass costs O(n) and removes at least one pair, so there can be up to n / 2 passes, for example on '((((...))))'.O(n)Each pass builds a new string of up to n characters.Every adjacent pair '()' is already fine and can be ignored. Erase all of them, and repeat, because erasing pairs can bring new pairs together, as in '(())'. When no pair is left, the string looks like some ')' followed by some '('. Each of those characters needs exactly one insertion, so the answer is the length of what remains.
- Repeat: replace every '()' in s with nothing.
- Stop when a pass changes nothing.
- Return the length of the remaining string.
class Solution {
public int minAddToMakeValid(String s) {
String prev;
do {
prev = s;
s = s.replace("()", "");
} while (!s.equals(prev));
return s.length();
}
}class Solution:
def minAddToMakeValid(self, s: str) -> int:
while True:
prev = s
s = s.replace("()", "")
if s == prev:
break
return len(s)class Solution {
public:
int minAddToMakeValid(string s) {
string prev;
do {
prev = s;
string next;
for (size_t i = 0; i < s.size(); i++) {
if (s[i] == '(' && i + 1 < s.size() && s[i + 1] == ')') i++;
else next += s[i];
}
s = next;
} while (s != prev);
return s.size();
}
};function minAddToMakeValid(s) {
let prev;
do {
prev = s;
s = s.split("()").join("");
} while (s !== prev);
return s.length;
}2Stack of unmatched brackets
O(n)Each character is pushed at most once and popped at most once.O(n)The stack can hold every character, for example when s is all '('.Use a stack to cancel pairs as you read. A '(' is pushed and waits. A ')' that finds a '(' on top closes it, so pop. A ')' that finds an empty stack, or another ')' on top, has nothing to close, so push it too. At the end the stack holds exactly the characters that never found a partner, and each of them needs one insertion.
- stack = empty.
- For each character c: if c is ')' and the top is '(', pop. Otherwise push c.
- Return the size of the stack.
class Solution {
public int minAddToMakeValid(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if (c == ')' && !stack.isEmpty() && stack.peek() == '(') stack.pop();
else stack.push(c);
}
return stack.size();
}
}class Solution:
def minAddToMakeValid(self, s: str) -> int:
stack = []
for c in s:
if c == ")" and stack and stack[-1] == "(":
stack.pop()
else:
stack.append(c)
return len(stack)class Solution {
public:
int minAddToMakeValid(string s) {
stack<char> st;
for (char c : s) {
if (c == ')' && !st.empty() && st.top() == '(') st.pop();
else st.push(c);
}
return st.size();
}
};function minAddToMakeValid(s) {
const stack = [];
for (const c of s) {
if (c === ")" && stack.length > 0 && stack[stack.length - 1] === "(") stack.pop();
else stack.push(c);
}
return stack.length;
}3Optimal (two counters)
O(n)One pass over the string, constant work per character.O(1)Just two integer counters.The stack only ever holds some ')' at the bottom with some '(' on top, and we only need its size. So keep two numbers instead. open counts the '(' still waiting for a partner. adds counts the ')' that arrived with nothing open: each forces one '(' to be inserted. A '(' raises open. A ')' lowers open if it is above zero, and otherwise raises adds. At the end, every '(' still open needs one ')' inserted, so the answer is adds plus open.
- open = 0, adds = 0.
- For each c: if c is '(', open++. Else if open > 0, open--. Else adds++.
- Return adds + open.
class Solution {
public int minAddToMakeValid(String s) {
int open = 0, adds = 0;
for (char c : s.toCharArray()) {
if (c == '(') open++;
else if (open > 0) open--;
else adds++;
}
return adds + open;
}
}class Solution:
def minAddToMakeValid(self, s: str) -> int:
open_count = 0
adds = 0
for c in s:
if c == "(":
open_count += 1
elif open_count > 0:
open_count -= 1
else:
adds += 1
return adds + open_countclass Solution {
public:
int minAddToMakeValid(string s) {
int open = 0, adds = 0;
for (char c : s) {
if (c == '(') open++;
else if (open > 0) open--;
else adds++;
}
return adds + open;
}
};function minAddToMakeValid(s) {
let open = 0, adds = 0;
for (const c of s) {
if (c === "(") open++;
else if (open > 0) open--;
else adds++;
}
return adds + open;
}Edge cases to test
- A string that is already valid (answer 0)
- Only '(' characters: every one needs a ')' (answer n)
- Only ')' characters: every one needs a '(' (answer n)
- ')(' : the order is wrong even though the counts are equal (answer 2)
- A ')' that comes before any '(' can never be matched by a later '('
- A single character
Hints
Hint 1
Read left to right and count the '(' that are still waiting to be closed. What does it mean when a ')' arrives while that count is 0?
Hint 2
A ')' with nothing open forces one insertion of '(' in front of it. A '(' still open at the end forces one insertion of ')' after it.
Hint 3
So the answer is the number of ')' that found nothing to close, plus the number of '(' still open after the last character. Two counters, one pass.
FAQ
What is the best time complexity for Minimum Add to Make Parentheses Valid?
Optimal (two counters) runs in O(n) time and O(1) extra space. One pass over the string, constant work per character.
Which pattern does Minimum Add to Make Parentheses Valid use?
It is a stack problem that uses the stack basics pattern. Other problems with the same pattern: Valid Parentheses, Baseball Game, Asteroid Collision.
Is there a brute force solution for Minimum Add to Make Parentheses Valid?
Yes. Brute force (keep erasing matched pairs) takes O(n²) time and O(n) space. Every adjacent pair '()' is already fine and can be ignored.
Which edge cases should I test for Minimum Add to Make Parentheses Valid?
A string that is already valid (answer 0); Only '(' characters: every one needs a ')' (answer n); Only ')' characters: every one needs a '(' (answer n); ')(' : the order is wrong even though the counts are equal (answer 2); A ')' that comes before any '(' can never be matched by a later '('; A single character.