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?
  1. A. [[2, 4], [6, 9], [12, 13]]
  2. B. [[2, 4], [6, 7], [12, 13]]
  3. C. [[2, 4], [6, 7], [8, 9], [12, 13]]
  4. 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

Exams that ask this topic