SDE & MLE Prep

986. Interval List Intersections

Problem

Two lists of closed intervals are each sorted and pairwise disjoint. Return their intersection: every range covered by an interval from both lists.

Example: [[0,2],[5,10],[13,23],[24,25]] and [[1,5],[8,12],[15,24],[25,26]] → [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]

Two pointers over the two sorted lists. Intersection = [max(starts), min(ends)] if non-empty. Advance the list whose interval ends first.

Complexity: O(m + n).

class Solution:
    def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:
        i = j = 0
        res = []
        while i < len(firstList) and j < len(secondList):
            lo = max(firstList[i][0], secondList[j][0])
            hi = min(firstList[i][1], secondList[j][1])
            if lo <= hi:
                res.append([lo, hi])
            if firstList[i][1] < secondList[j][1]:
                i += 1
            else:
                j += 1
        return res