Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE

Problem: Find the minimum number of brackets to insert so that a string of '(' and ')' becomes balanced.

Problem: Find the minimum number of brackets to insert so that a string of '(' and ')' becomes balanced.
def min_add(s):
    open_ = add = 0
    for c in s:
        if c == "(":
            open_ += 1
        elif open_:
            open_ -= 1
        else:
            add += 1
    return add + open_
print(min_add("())(("), min_add(")))("), min_add("(()())"))
What is printed?
  1. A. 2 4 0
  2. B. 3 4 0
  3. C. 3 2 0
  4. D. 1 4 0

Correct answer: B. 3 4 0

open_ counts unmatched '('; a ')' with nothing to match needs an inserted '(' (add). At the end every still-open '(' needs a ')'. "())((": one unmatched ')' + two open '(' → 3. ")))(": 3 + 1 → 4. Returning only |#'(' − #')'| (1 for the first string) ignores order. O(n), O(1).

More Coding Interview Problems questions

Exams that ask this topic