Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Problem: Return the minimum number of parentheses to insert to make a string valid.

Problem: Return the minimum number of parentheses to insert to make a string valid.
def min_add(s):
    open_, add = 0, 0
    for c in s:
        if c == '(': open_ += 1
        elif open_: open_ -= 1
        else: add += 1
    return add + open_
print(min_add("())((("), min_add(")))((("))
What is printed?
  1. A. 2 3
  2. B. 4 3
  3. C. 4 6
  4. D. 1 6

Correct answer: C. 4 6

Unmatched ')' each need a '(' inserted before them (add), and unmatched '(' at the end each need a ')' (open_). '())(((' has 1 stray ')' and 3 open '(' → 4; ')))(((' has 3 and 3 → 6.

More Coding Interview Problems questions

Exams that ask this topic