Data Structures & AlgorithmsHardProduct Company SDE · stack OA

Problem: Minimum insertions of brackets to make the string '(()))(' valid, found by this greedy scan?

Problem: Minimum insertions of brackets to make the string '(()))(' valid, found by this greedy scan?
s = '(()))('
bal = 0
ins = 0
for c in s:
    if c == '(':
        bal += 1
    else:
        if bal:
            bal -= 1
        else:
            ins += 1
print(ins + bal)
What is printed?
  1. A. 1
  2. B. 2
  3. C. 3
  4. D. 0

Correct answer: B. 2

One unmatched ')' is inserted-fixed by the scan and one '(' at the end stays open, so 2 insertions are needed. Counting only the unmatched ')' gives the trap 1.

More Coding Interview Problems questions

Exams that ask this topic