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?- A. 2 3
- B. 4 3
- C. 4 6
- 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
- Problem: A ramp is a pair i < j with a[i] ≤ a[j]; its width is j − i. Find the maximum width using a decreasing stack of candidate left…
- Problem: Return the k most frequent words, ties broken alphabetically. python from collections import Counter def topk(words, k): c =…
- Design a set supporting insert, delete and getRandom (uniform) all in O(1) average time. Which design works?
- Problem: Rotate a linked list to the right by k places. python class N: def init(s, v, nx=None): s.v, s.nx = v, nx def rotate(h, k): n, t…
- Problem: Partition a linked list so that all nodes with values < x come before nodes ≥ x, preserving relative order within each part…
- List A has a nodes before it joins a shared tail of c nodes; list B has b nodes before the same tail, with a ≠ b. Pointer p walks A and…