Advanced topics · Exercise 92 of 100

Valid parentheses

For a string containing only round parentheses, keep a count of unmatched opening parentheses. Add one for each opening symbol and subtract one for each closing symbol. A valid string keeps the count at or above zero throughout and ends at zero, so each closing symbol has an earlier partner and every opening symbol gets used.

Try it yourself

Scan the string (()))( from left to right, numbering the symbols from 1. At which position does a closing parenthesis first lack an earlier unmatched opening parenthesis?

One-step hint

Number the symbols and keep a count of unmatched openings. At each closing symbol, check the count before subtracting one.

Worked solution
  1. The first two symbols raise the count to 2. The closing symbols at positions 3 and 4 use both openings and bring the count back to zero.
  2. The closing symbol at position 5 takes the count below zero, so 5 is the first position without a partner.
DSA compiler