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?- A. 2 4 0
- B. 3 4 0
- C. 3 2 0
- 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
- Problem: Parcels 1..5 are pushed onto a loading stack in that order (pops may happen at any time). Decide whether a given pop order is…
- Problem: People queue at a single counter; person i wants t[i] tickets, buys one per second and, if still needing more, goes to the back…
- Problem: Regroup a linked list so that all nodes at odd positions (1st, 3rd, …) come first, followed by the even positions, keeping…
- Problem: Rotate a linked list to the right by k places (k may exceed the length). python class Node: def init(self, v, nxt=None): self.v…
- Problem: Each rescue boat carries at most two people and at most limit kg. Find the minimum number of boats (greedy: pair the heaviest…
- Problem: Count how many query words are subsequences of a long log string, using per-letter position lists and binary search (instead of…