Data Structures & AlgorithmsHardProduct Company SDE · stack OA
Problem: Minimum insertions of brackets to make the string '(()))(' valid, found by this greedy scan?
Problem: Minimum insertions of brackets to make the string '(()))(' valid, found by this greedy scan?
s = '(()))('
bal = 0
ins = 0
for c in s:
if c == '(':
bal += 1
else:
if bal:
bal -= 1
else:
ins += 1
print(ins + bal)What is printed?- A. 1
- B. 2
- C. 3
- D. 0
Correct answer: B. 2
One unmatched ')' is inserted-fixed by the scan and one '(' at the end stays open, so 2 insertions are needed. Counting only the unmatched ')' gives the trap 1.
More Coding Interview Problems questions
- Problem: How many contiguous subarrays of [1, 2, 1, 2, 1, 3, 1] contain exactly 2 odd numbers? python a = [1, 2, 1, 2, 1, 3, 1] k = 2 cnt…
- Problem: How many subsets of {1, 2, 3, 4, 5, 6, 7, 8} have a sum of exactly 10? python cnt = 0 for m in range(1 << 8): if sum(i + 1 for i…
- Problem: After running Floyd-Warshall on a directed graph with possibly negative edges, which check correctly detects that vertex i lies…
- Problem: A road graph has V = 10^5 vertices and E = 3 10^5 edges, all weights non-negative, and you need shortest paths from one source…
- Problem: For the shortest subarray with sum at least S in an array of positive integers, a two-pointer sweep is used: extend the right…
- Problem: Weighted interval scheduling (each job has a start, finish and profit; choose a set of non-overlapping jobs to maximise profit)…