Minimum Add to Make Parentheses Valid
Medium
Topics
Given a parentheses string s, return the minimum number of ( or ) insertions needed to make it valid.
Example 1
Input: s = "())" Output: 1
Example 2
Input: s = "((("
Output: 3
Example 3
Input: s = "()" Output: 0
Constraints
- 1 <= s.length <= 1000
- s consists of ( and ) only.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Scan left to right and decide each character's fate the moment you see it. An opening bracket always becomes an unmatched open. A closing bracket either consumes an unmatched open, or there is nothing to consume and it needs an opening bracket inserted before it — a decision that is never revisited, which is what makes a single greedy pass correct.
At the end, every still-unmatched open needs a closing bracket. The answer is the sum of the two. Only the count of unmatched opens ever matters, never which ones, so a stack of characters is replaceable by one integer.
Approach
- Keep
openfor unmatched opening brackets andaddfor insertions already committed to. - On
(, incrementopen. - On
), decrementopenif it is positive, otherwise incrementadd. - Return
add + open.
Dry Run
s = "())("
c open add note
( 1 0 opens
) 0 0 closes an open
) 0 1 nothing open, insert a ( before it
( 1 1 opens
answer add + open = 1 + 1 = 2Complexity
- Time — O(n): one pass, constant work per character.
- Space — O(1): two integers.
Common Pitfalls
- Returning only one of the two counts. Both deficits are real and independent.
- Comparing the totals:
abs(count('(') - count(')'))is 0 for"())(", but the string needs two insertions. Balance is necessary and not sufficient — order matters. - Letting
opengo negative instead of booking an insertion. The final sum then cancels the two deficits against each other and understates the answer. - Using a stack of characters. It is correct and is the honest first answer, but it is O(n) space for information you never read back; say that out loud and then collapse it to a counter.
- Assuming a greedy left-to-right pass needs justification beyond the invariant. It does not: an unmatchable
)can only ever be fixed by an insertion to its left, so the choice is forced, not greedy-and-hopeful.
Full Solution — all languages
class Solution:
def minAddToMakeValid(self, s):
open_ = add = 0
for c in s:
if c == "(":
open_ += 1
elif open_ > 0:
open_ -= 1
else:
add += 1
return add + open_import java.util.*;
class Solution {
public int minAddToMakeValid(String s) {
int open = 0, add = 0;
for (char c : s.toCharArray()) {
if (c == '(') open++;
else if (open > 0) open--;
else add++;
}
return add + open;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int minAddToMakeValid(string s) {
int open = 0, add = 0;
for (char c : s) {
if (c == '(') open++;
else if (open > 0) open--;
else add++;
}
return add + open;
}
};/**
* @param {string} s
* @return {number}
*/ var minAddToMakeValid = function(s) {
let open = 0, add = 0;
for (const c of s) {
if (c === '(') open++;
else if (open > 0) open--;
else add++;
}
return add + open;
};