Minimum Add to Make Parentheses Valid (LeetCode 921): Solution and Explanation
You get a string of ( and ). One move inserts a single parenthesis anywhere. Return the fewest moves that make the string valid, meaning every ( is closed by a later ) and every ) closes an earlier (.
Intuition
A string is valid exactly when, reading left to right, the number of ) never gets ahead of the number of (, and the two counts are equal at the end. So there are only two ways to be broken: a ) that shows up with nothing open before it, and a ( that is still open when the string ends.
When a ) arrives and nothing is open, nothing later in the string can fix it, because a partner has to come before it. The cheapest fix is a single ( inserted in front of it. That ) is then used up and the scan continues.
When the scan ends, each ( still open needs one ) appended. These two kinds of fixes never overlap and each one is forced, so their sum is the minimum.
You could keep a real stack of ( characters, but every push is a ( and every pop removes one, so only its size matters. A single counter replaces it.
Approach: Balance counter
- Set
open = 0(unmatched(so far) andadded = 0(insertions made so far). - For each
(, incrementopen. - For each
): ifopen > 0, it closes one waiting(, so decrementopen. Otherwise incrementaddedto insert a(before it. - Return
added + open: the inserted(plus one)for every(left open.
Step-by-step example
s = "())"
- Start with open = 0 and added = 0.
- Index 0 is '(': open becomes 1.
- Index 1 is ')': open is 1, so it closes that '(' and open drops to 0.
- Index 2 is ')': open is 0, so there is nothing to close. Insert '(' before it, and added becomes 1.
- The scan ends with open = 0, so nothing is appended. The answer is 1 + 0 = 1.
Code: Python, Java, C++
1class Solution:
2 def minAddToMakeValid(self, s: str) -> int:
3 open_count = 0
4 added = 0
5 for ch in s:
6 if ch == '(':
7 open_count += 1
8 elif open_count > 0:
9 open_count -= 1
10 else:
11 added += 1
12 return added + open_count1class Solution {
2 public int minAddToMakeValid(String s) {
3 int open = 0;
4 int added = 0;
5 for (char ch : s.toCharArray()) {
6 if (ch == '(') {
7 open++;
8 } else if (open > 0) {
9 open--;
10 } else {
11 added++;
12 }
13 }
14 return added + open;
15 }
16}1class Solution {
2public:
3 int minAddToMakeValid(string s) {
4 int open = 0;
5 int added = 0;
6 for (char ch : s) {
7 if (ch == '(') {
8 open++;
9 } else if (open > 0) {
10 open--;
11 } else {
12 added++;
13 }
14 }
15 return added + open;
16 }
17};Time and space complexity
O(n)
Each character is read once and does a constant amount of work.
O(1)
Only two integer counters are kept, whatever the length of the string.
Other approaches
Explicit stack (time O(n), space O(n))
Push every (; on ) pop if the stack is non-empty, otherwise count an insertion. The answer is insertions plus the final stack size. It is the same logic with O(n) memory.
Repeatedly delete "()" (time O(n²), space O(n))
Keep removing adjacent "()" pairs until none remain. What is left looks like ")))(((" and its length is the answer. It is easy to reason about but can take O(n²) time.
Common mistakes
- Returning
abs(count('(') - count(')')). For "))((" the counts are equal, but the string needs 4 insertions because the order is wrong. - Letting the balance go negative instead of counting an insertion. A negative balance would let a later
(cancel an earlier), which is not a valid match. - Forgetting the leftover
openat the end and returning onlyadded. - Decrementing
openwithout checking it is positive first.
Frequently asked questions
Why is the greedy count the minimum?
Each lone ) needs some ( before it that is not used elsewhere, and each ( still open at the end needs some ) after it. Every insertion fixes at most one of these problems, and the scan counts exactly one insertion per problem.
Is this a stack problem if no stack is used?
It is the stack idea from Valid Parentheses. With only one bracket type the stack holds nothing but (, so a counter that tracks its size is enough.
How is this different from Minimum Remove to Make Valid Parentheses?
Here you insert characters and only return a count. In that problem you delete characters and must return one valid string, so you need to remember the positions of the unmatched brackets.
What is the time complexity of Minimum Add to Make Parentheses Valid?
O(n) time and O(1) extra space with the two-counter scan.