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("(()))("))- A. (5, 1, 4) (6, 3, 3) (2, 1, 1)
- B. (4, 1, 3) (6, 3, 3) (2, 1, 1)
- C. (5, 1, 4) (3, 3, 0) (1, 1, 0)
- 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.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Boyer–Moore majority vote WITHOUT the verification pass, returning (candidate, final counter). What is printed? python def vote(a): cand…
- Inversions counted during merge sort (pairs i < j with a[i] > a[j]). What is printed? python def inv(a): if len(a) <= 1: return a, 0 m =…
- One Hoare partition with the FIRST element (6) as pivot. What is printed (array after the partition, returned index)? python def hoare(a)…
- Counting palindromic substrings (by position) with centre expansion over 2n − 1 centres. What is printed? python def pal(s): c = 0 for…
- Sum over all subarrays of (max − min), computed as Σ max − Σ min with two monotonic-stack passes, checked against brute force. What is…
- Merging files costs the size of the result each time. Compare the greedy 'always merge the two smallest' (heap) with merging left to right…