Minimum Add to Make Parentheses Valid

Medium

Topics
StringStackGreedy

Given a parentheses string s, return the minimum number of ( or ) insertions needed to make it valid.

Example 1

(0)1)2
needs a ( before it
The answer is the two added together, 1 — no stack required, since only the counts matter, not the positions.
Cells are the characters of the string; the small numbers underneath are indices.
Input:  s = "())"
Output: 1

Example 2

(0(1(2
needs a ) after it
Input:  s = "((("
Output: 3

Example 3

(0)1
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

  1. Keep open for unmatched opening brackets and add for insertions already committed to.
  2. On (, increment open.
  3. On ), decrement open if it is positive, otherwise increment add.
  4. 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 = 2

Complexity

  • 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 open go 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_
Asked at Meta
SensAI
Beta
Tap the mic to stop voice mode