Interval List Intersections (LeetCode 986): Solution and Explanation

Medium
Array
Two Pointers
Line Sweep

Two sorted lists of disjoint closed intervals are walked together with one pointer each. For the current pair the overlap is [max of the starts, min of the ends] when that range is not empty, and the interval that ends first is retired because nothing later in the other list can reach back to it.

Intuition

Two closed intervals [a1, b1] and [a2, b2] share points exactly when the later start is not past the earlier end. That shared piece is [max(a1, a2), min(b1, b2)], so one comparison both detects and builds the overlap.

Both lists are sorted and disjoint, which is the same setup as merging two sorted arrays. Once an interval ends, every interval after it in the other list starts even further right, so the interval that ends first can never overlap anything else. Retiring it is always safe, and the walk finishes in one pass.

Approach: Two pointers

  1. Start with an empty result and pointers i = 0 into firstList and j = 0 into secondList.
  2. While both pointers are inside their lists, set lo = max(firstList[i][0], secondList[j][0]) and hi = min(firstList[i][1], secondList[j][1]).
  3. If lo <= hi, append [lo, hi] to the result. Equal values give a single point such as [5, 5].
  4. If firstList[i] ends before secondList[j], advance i; otherwise advance j.
  5. When either list runs out, return the result. It is already sorted because both pointers only move right.

Step-by-step example

firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24],[25,26]]
  1. [0,2] vs [1,5]: lo = 1, hi = 2, record [1,2]. [0,2] ends first, so i moves to [5,10].
  2. [5,10] vs [1,5]: lo = 5, hi = 5, record the single point [5,5]. [1,5] ends first, so j moves to [8,12].
  3. [5,10] vs [8,12]: record [8,10], advance i. [13,23] vs [8,12]: lo = 13 > hi = 12, no overlap, advance j.
  4. [13,23] vs [15,24]: record [15,23], advance i. [24,25] vs [15,24]: record [24,24], advance j.
  5. [24,25] vs [25,26]: record [25,25], advance i. firstList is used up, so the answer is [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]].

Code: Python, Java, C++

1class Solution:
2    def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:
3        result = []
4        i = j = 0
5        while i < len(firstList) and j < len(secondList):
6            lo = max(firstList[i][0], secondList[j][0])
7            hi = min(firstList[i][1], secondList[j][1])
8            if lo <= hi:
9                result.append([lo, hi])
10            if firstList[i][1] < secondList[j][1]:
11                i += 1
12            else:
13                j += 1
14        return result
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(m + n)

Every iteration advances exactly one pointer, so the loop runs at most m + n times and each iteration does constant work.

Space

O(1)

Only two pointers and two bounds are kept. The output list itself can hold up to m + n - 1 intervals and is not counted as extra space.

Other approaches

Compare every pair (time O(m * n), space O(1))

Test each interval of firstList against each interval of secondList and keep the non-empty overlaps. It is correct but ignores the sorting, and the output still has to come out in order.

Event sweep (time O((m + n) log(m + n)), space O(m + n))

Turn every interval into a start event and an end event, sort them, and track how many intervals are open; a range where the count is 2 is an intersection. It generalises to k lists but needs care with closed endpoints and an extra sort.

Common mistakes

  • Using lo < hi instead of lo <= hi. The intervals are closed, so touching endpoints like [1,5] and [5,10] intersect at [5,5].
  • Advancing both pointers after a match. The interval that ends later may still overlap the next interval in the other list, as [0,20] does with several intervals of secondList.
  • Advancing based on start points instead of end points. The interval to retire is the one that ends first.
  • Forgetting that either list may be empty, in which case the answer is an empty list.

Frequently asked questions

Why is it safe to drop the interval that ends first?

The next interval in the other list starts after the current one there ends, and that end is at or beyond the end of the interval being dropped. So every remaining interval in the other list starts after the dropped one is over and cannot share a point with it.

What happens when both intervals end at the same point?

Either pointer can move. The code advances j in that case. The other interval will then be compared with the next interval of secondList, which starts after the shared end, so no overlap is lost or duplicated.

Can the result ever need merging or sorting?

No. Each list is disjoint and sorted, and both pointers only move forward, so the intersections come out sorted and never overlap one another.

How is this related to merging two sorted arrays?

It is the same two pointer walk. Instead of copying the smaller element, each step reports the overlap of the two current items and then moves past the one that finishes first.