Interval List Intersections
Return intersections between two sorted lists of pairwise-disjoint closed intervals.
Open on LeetCode ↗Intuition
Comparing every interval in one list with every interval in the other wastes their sorted, disjoint structure. For the current pair, any overlap is determined by the later start and earlier end. After that comparison, the interval ending first cannot overlap any later interval across the other list. Advancing that pointer yields a linear merge-style scan.
Two sorted, internally disjoint interval lists invite a two-pointer merge. After processing a pair, the earlier-ending interval is permanently exhausted relative to all future intervals.
Approach
Compare one interval from each list
Use pointers i and j. Compute start = max(first[i].start, second[j].start) and end = min(first[i].end, second[j].end) for the only possible overlap between the current intervals.
Emit closed-boundary intersections
Append [start, end] when start <= end. Equality is included because these are closed intervals and a shared endpoint is a valid one-point intersection.
Discard the interval that finishes first
Advance i when the first interval's end is smaller; otherwise advance j. If ends are equal, advancing either is safe because neither interval can overlap a future interval from the opposite disjoint list.
Solution
Common pitfalls
Using union boundaries
start = min(a[0], b[0]) end = max(a[1], b[1])
start = max(a[0], b[0]) end = min(a[1], b[1])
Intersection keeps only points inside both intervals.
Dropping endpoint intersections
if start < end:
if start <= end:
Closed intervals intersect when one ends exactly where the other begins.
Advancing the later-ending interval
if a[1] < b[1]:
j += 1if a[1] < b[1]:
i += 1The earlier-ending interval cannot reach any later counterpart and is the one that must be discarded.
Edge cases
The loop never runs and returns an empty result.
The non-strict overlap check returns that endpoint as [x, x].
The contained interval is returned, then its pointer advances because it ends first.