Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE

Problem: Two engineers list their free slots as sorted, internally disjoint closed intervals. Return every common free interval.

Problem: Two engineers list their free slots as sorted, internally disjoint closed intervals. Return every common free interval.
def intersect(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(intersect([(1, 4), (6, 9), (12, 15)], [(3, 7), (9, 13)]))
What is printed?
  1. A. [(3, 7), (9, 13)]
  2. B. [(1, 7), (6, 13), (12, 15)]
  3. C. [(3, 4), (6, 7), (9, 9), (12, 13)]
  4. D. [(3, 4), (6, 7), (12, 13)]

Correct answer: C. [(3, 4), (6, 7), (9, 9), (12, 13)]

The overlap of two intervals is [max of starts, min of ends] when non-empty; then advance whichever interval ends first, since it cannot meet anything later. Closed intervals that only touch still intersect: (6, 9) and (9, 13) share the single point (9, 9). Dropping it (lo < hi) gives the second option. O(|A| + |B|).

More Coding Interview Problems questions

Exams that ask this topic