Interval List Intersections
Explanation & Solution
Description
You are given two lists of closed intervals, firstList and secondList, where firstList[i] = [startᵢ, endᵢ] and secondList[j] = [startⱼ, endⱼ]. Each list of intervals is pairwise disjoint and in sorted order.
Return the intersection of these two interval lists.
A closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b.
The intersection of two closed intervals is a set of real numbers that is either empty or represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3].
Input: firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24],[25,26]]
Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
Explanation: The intersections are computed pairwise between overlapping intervals from both lists.
Constraints
0 <= firstList.length, secondList.length <= 1000firstList.length + secondList.length >= 10 <= startᵢ < endᵢ <= 10⁹(except single-point intervals wherestartᵢ == endᵢ)0 <= startⱼ < endⱼ <= 10⁹(except single-point intervals wherestartⱼ == endⱼ)- Each list is pairwise disjoint and sorted by start time
Approach
Intervals pattern
1. Initialize Two Pointers
- Set
i = 0to point at the first interval infirstList - Set
j = 0to point at the first interval insecondList - Create an empty
resultarray to collect intersections
2. Compare the Current Pair of Intervals
- At each step we look at
firstList[i]andsecondList[j] - Compute the potential overlap:
lo = max(firstList[i][0], secondList[j][0])— the later of the two start timeshi = min(firstList[i][1], secondList[j][1])— the earlier of the two end times
3. Check If an Intersection Exists
- If
lo <= hi, the two intervals overlap and their intersection is[lo, hi] - Push
[lo, hi]into the result array - If
lo > hi, the intervals do not overlap — no intersection is added
4. Advance the Pointer With the Smaller End
- If
firstList[i][1] < secondList[j][1], incrementi - The interval in
firstListends sooner, so it cannot overlap with any future interval insecondList - Otherwise, increment
j - The interval in
secondListends sooner (or at the same time) - This greedy choice ensures we never miss an intersection
5. Loop Until One List Is Exhausted
- Once either
iorjgoes out of bounds, there can be no more intersections - Return the
resultarray
Key Insight
- The intersection of
[a, b]and[c, d]exists precisely whenmax(a, c) <= min(b, d), and equals[max(a, c), min(b, d)] - Because both lists are sorted and disjoint, advancing the pointer whose interval ends first is always correct — that interval cannot intersect any later interval in the other list
Visualization
Press play to start visualization