DSA Factory
Free Stacks and queues lessonsStacks and queues · Stage 1 · Matching brackets · Step 1

How many brackets are missing

Count the fewest brackets to add so a row of round brackets matches, noticing that a stack of identical brackets is just a counter. About 12 minutes.

A counter instead of a stack

Reading a row of round brackets from the left, an opening bracket waits for a closer. A closing bracket cancels the nearest waiting opener. When there is only one kind of bracket, all waiting openers look the same, so you do not need a stack to remember which is which. A number saying how many are waiting is enough.

Opening bracket: add one to the waiting count.
Closing bracket: cancels one waiting opener, if any.
In code
if ch == "(":
    open_count += 1
elif open_count > 0:
    open_count -= 1
Brackets of the text ( ) ) ( (. Count the missing ones.
(
0
)
1
)
2
(
3
(
4
i

An opener. Waiting: 1. Additions: 0.

Move 1 of 5

Two kinds of damage

A closer that finds no waiting opener can never be matched by anything before it. The only fix is to add an opener in front of it, so count one addition.

At the end, every opener still waiting needs a closer added after it. So the answer is the number of additions made on the way, plus the number of openers still waiting.

Closer with nothing waiting: needs an opener added.
Answer: additions so far plus openers still waiting.
In code
else:
    adds += 1
return adds + open_count
Quick check

How many brackets must be added to make the text ) ) ( ( match?

  1. A4
  2. B2
  3. C0
Show the answer

4. Both closers need an opener in front, and both openers need a closer after.

Your problem

Fewest brackets to add

You are given a string s made only of the characters ( and ). In one move you may insert a bracket of either kind at any position. Return the fewest insertions that make s balanced, meaning every opening bracket is matched by a later closing bracket.

Example
s = "())((" → 3

0 ≤ length of s ≤ 100,000 · s has only ( and )

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve