Minimum Add to Make Parentheses Valid (LeetCode 921): Solution and Explanation

Medium
String
Stack
Greedy

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

  1. Set open = 0 (unmatched ( so far) and added = 0 (insertions made so far).
  2. For each (, increment open.
  3. For each ): if open > 0, it closes one waiting (, so decrement open. Otherwise increment added to insert a ( before it.
  4. Return added + open: the inserted ( plus one ) for every ( left open.

Step-by-step example

s = "())"
  1. Start with open = 0 and added = 0.
  2. Index 0 is '(': open becomes 1.
  3. Index 1 is ')': open is 1, so it closes that '(' and open drops to 0.
  4. Index 2 is ')': open is 0, so there is nothing to close. Insert '(' before it, and added becomes 1.
  5. 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_count
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Balance counter O(n)
Explicit stack O(n)
Repeatedly delete "()" O(n²)
Time

O(n)

Each character is read once and does a constant amount of work.

Space

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 open at the end and returning only added.
  • Decrementing open without 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.