Data Structures & AlgorithmsHardGoogle · Flipkart interview
Problem: Intersect two lists of disjoint, sorted closed intervals.
Problem: Intersect two lists of disjoint, sorted closed intervals.
def inter(A, B):
i = j = 0; out = []
while i < len(A) and j < len(B):
lo = max(A[i][0], B[j][0]); hi = min(A[i][1], B[j][1])
if lo <= hi: out.append([lo, hi])
if A[i][1] < B[j][1]: i += 1
else: j += 1
return out
print(inter([[1, 4], [6, 9], [12, 15]], [[2, 7], [8, 13]]))What is printed?- A. [[2, 4], [6, 9], [12, 13]]
- B. [[2, 4], [6, 7], [12, 13]]
- C. [[2, 4], [6, 7], [8, 9], [12, 13]]
- D. [[1, 7], [6, 13]]
Correct answer: C. [[2, 4], [6, 7], [8, 9], [12, 13]]
Advance whichever interval ends first, since it cannot meet anything later. [2,7] meets [1,4] in [2,4] and [6,9] in [6,7]; [8,13] meets [6,9] in [8,9] and [12,15] in [12,13]. Forgetting that [6,9] meets both B intervals drops [8,9].
More Coding Interview Problems questions
- Problem: Cars drive toward a target on a one-lane road. A car that catches a slower car ahead joins it as a fleet (moving at the slower…
- Problem: Return the minimum number of parentheses to insert to make a string valid. python def minadd(s): open, add = 0, 0 for c in s: if…
- 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…