Data Structures & AlgorithmsVery hardProduct company OA

Minimum number of brackets to INSERT to make a string balanced, returned as (total, unmatched ')', unmatched '('). What is printed?

Minimum number of brackets to INSERT to make a string balanced, returned as (total, unmatched ')', unmatched '('). What is printed?
def fix(s):
    open_, add = 0, 0
    for ch in s:
        if ch == "(": open_ += 1
        elif open_: open_ -= 1
        else: add += 1
    return add + open_, add, open_
print(fix("())(()((("), fix(")))((("), fix("(()))("))
  1. A. (5, 1, 4) (6, 3, 3) (2, 1, 1)
  2. B. (4, 1, 3) (6, 3, 3) (2, 1, 1)
  3. C. (5, 1, 4) (3, 3, 0) (1, 1, 0)
  4. D. (3, 1, 2) (6, 3, 3) (2, 1, 1)

Correct answer: A. (5, 1, 4) (6, 3, 3) (2, 1, 1)

Scan once: a ')' with no open '(' needs an inserted '('; every '(' still open at the end needs a ')'. '())(()(((': one stray ')' and 4 open → 5. ')))(((': 3 + 3 = 6 (the order matters – the same characters as '((()))' would need 0). '(()))(': one stray ')' and one open → 2. A single counter that may go negative and is reported as |count| gives 0 for ')))(((' – the classic wrong shortcut.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic