15% off all plans & roadmaps Use code

See plans

Interval List Intersections

Updated

TL;DR: You get two sorted lists of disjoint closed intervals and must return every overlap between them. Walk both lists with one pointer each, record the overlap of the current pair, then advance the pointer of whichever interval ends first.

Problem

You are given two lists of closed intervals, firstList and secondList. Each interval has a start and an end, so firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Inside each list, the intervals are pairwise disjoint and in sorted order.

Return the intersection of these two interval lists.

A closed interval [a, b], with a <= b, is the set of real numbers x where a <= x <= b. The intersection of two closed intervals is either empty or another closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3].

Example 1

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]]

Example 2

Input: firstList = [[1,3],[5,9]], secondList = []
Output: []

Constraints

  • 0 <= firstList.length, secondList.length <= 1000
  • firstList.length + secondList.length >= 1
  • 0 <= starti < endi <= 10^9
  • endi < starti+1
  • 0 <= startj < endj <= 10^9
  • endj < startj+1

Constraints that matter

  • Each list is sorted and disjoint, so a pointer that only moves forward can visit every interval once. That order is the property the fast solution depends on.
  • Lengths up to 1000 make O(n * m) about 10^6 pair checks. That fits the limits, but the sorted order gives O(n + m) for free, and interviewers expect you to use it.
  • Values up to 10^9 fit in a 32-bit signed int, so Java, C++, C# and Go need no 64-bit type for the overlap bounds.
  • Empty lists are allowed, so the loop must test both pointers against their list lengths before reading an element.
  • Intervals are closed, so a single shared endpoint counts as an intersection. That forces the overlap test to use <=.

View on LeetCode

Hints

Hint 1

Both lists are sorted, and each list is disjoint inside itself.

Hint 2

A beginner checks every interval in firstList against every interval in secondList.

Solution

Intuition

Both lists are sorted, and each list is disjoint inside itself. That order decides the method. Walk the two lists from left to right with one pointer in each, the same way you merge two sorted arrays.

Picture two stacks of meeting-room bookings, each sorted by start time. The top card of each stack is the pointer, and the booking that ends first gets pulled off its stack.

This is a line sweep with two pointers. Picture a vertical line moving left to right across the number line. At any moment, only one interval from each list matters, the pair the pointers point at. Compare that pair, record their overlap if one exists, then move the line past whichever interval ends first.

The discard rule is safe. Suppose a ends before b ends. The next interval in the other list starts after b ends, so it also starts after a ends. Nothing later can meet a, so dropping a loses no overlap. The same argument holds when b ends first.

Interview tips. Say the sorted, disjoint property out loud first, because the whole solution depends on it. Then state the brute force cost. With lengths up to 1000, O(n * m) is about 10^6 steps, which fits the limits, but it ignores the order you were given. Explain the discard rule with its short proof before you write any code.

Watch the pattern animation

Worked example

Input: firstList = [[1,3],[5,9]], secondList = []
Output: []
Explanation: The second list is empty, so no pair of intervals exists to compare. Every algorithm must return an empty list here. The two-pointer loop stops at its first test, which is why the dry runs below also show Example 1 from the statement.

Approach 1: Brute force

A beginner checks every interval in firstList against every interval in secondList. For each pair, the overlap runs from the larger start to the smaller end. The pair overlaps when that start is at most that end. The method never uses the sorted order, so it tests every pair, including pairs that sit far apart on the number line.

Steps

  1. Create an empty result list.
  2. For each interval a in firstList, loop over every interval b in secondList.
  3. Set lo = max(a[0], b[0]) and hi = min(a[1], b[1]).
  4. If lo <= hi, append [lo, hi] to the result.
  5. Return the result.

Dry run

The verified example has an empty secondList. The outer loop visits [1, 3] and then [5, 9]. The inner loop runs zero times each time, so no pair is ever compared. result stays empty, which matches the expected output [].

On Example 1 from the statement, the same code tests 4 * 4 = 16 pairs. Because both lists are sorted and disjoint, the overlapping pairs come out in sorted order when the outer loop runs over firstList. The six intersections appear as [1,2], [5,5], [8,10], [15,23], [24,24], [25,25], so no final sort is needed.

Complexity

TimeO(n * m)
SpaceO(1) auxiliary, excluding the output

Let n be the length of firstList and m the length of secondList. The two loops nest, so the loop body runs exactly n * m times, and each run does constant work. Besides the output list, the code keeps only a few variables, so the extra space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:
        result = []
        for a in firstList:
            for b in secondList:
                # The overlap of two closed intervals runs from the larger start to the smaller end.
                lo = max(a[0], b[0])
                hi = min(a[1], b[1])
                if lo <= hi:
                    result.append([lo, hi])
        return result

The Line Sweep infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Line Sweep

Part of Greedy Patterns

Approach 2: Two pointers (line sweep)OptimalLine Sweep

What is slow: the brute force checks all n * m pairs. Most of those pairs sit far apart and cannot meet, yet each one still costs a comparison.

The insight that fixes it: the lists are sorted and disjoint, so only one interval per list is active at a time. When one interval ends before the other, it cannot meet any later interval in the other list. Drop it and never look at it again.

Each step moves exactly one pointer forward, and neither pointer ever moves back. That keeps the walk linear in the total number of intervals.

Steps

  1. Set i = 0 and j = 0, and start with an empty result.
  2. While i is inside firstList and j is inside secondList, read a = firstList[i] and b = secondList[j].
  3. Set lo = max(a[0], b[0]) and hi = min(a[1], b[1]). If lo <= hi, append [lo, hi].
  4. If a[1] < b[1], increment i. Otherwise increment j.
  5. When either pointer leaves its list, return the result.

Dry run

On the verified example, secondList is empty, so the loop test fails at once.

Stepijlohiresult
Start00n/an/a[]
Loop test: j < 0 fails00n/an/a[]
Return00n/an/a[]

To see the pointers move, here is Example 1 from the statement. Each row shows the state before the comparison.

Stepija = firstList[i]b = secondList[j]overlapresult after stepmove
100[0,2][1,5][1,2][[1,2]]i
210[5,10][1,5][5,5][[1,2],[5,5]]j
311[5,10][8,12][8,10]adds [8,10]i
421[13,23][8,12]none, since 13 > 12no changej
522[13,23][15,24][15,23]adds [15,23]i
632[24,25][15,24][24,24]adds [24,24]j
733[24,25][25,26][25,25]adds [25,25]i

After step 7, i is 4 and leaves firstList. The result matches Example 1 in order.

Complexity

TimeO(n + m)
SpaceO(1) auxiliary, excluding the output

Let n and m be the lengths of the two lists. Each loop iteration moves exactly one pointer forward by one index. The loop stops when either pointer reaches the end of its list, so there are at most n + m iterations. Each iteration does constant work, and the code keeps only two indices and a few temporaries, so the extra space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:
        result = []
        i, j = 0, 0
        while i < len(firstList) and j < len(secondList):
            a, b = firstList[i], secondList[j]
            lo = max(a[0], b[0])
            hi = min(a[1], b[1])
            if lo <= hi:
                result.append([lo, hi])
            # The interval that ends first cannot meet anything later in the other list.
            if a[1] < b[1]:
                i += 1
            else:
                j += 1
        return result

Common mistakes

  • Advancing on starts with if a[0] < b[0]: i += 1. A long interval such as [0, 10] gets dropped before it meets [1, 2], [3, 4] and [5, 6]. Advance on the end instead, with a[1] < b[1], because the interval that ends first is the finished one.
  • Testing overlap with if lo < hi. This drops single-point intersections such as [5, 5] in Example 1. Closed intervals share their endpoints, so the test must be lo <= hi.
  • Moving both pointers on every pass with i += 1; j += 1. This skips intervals that can still meet the next one, such as [8, 12] against the current [5, 10]. Move only the pointer of the interval that ends first.
  • Swapping the bounds, as in lo = min(a[0], b[0]) and hi = max(a[1], b[1]). That builds the union of the two intervals, not their overlap. Use the larger start and the smaller end.
  • Appending before the check, as in result.append([lo, hi]) placed above if lo <= hi. Empty overlaps then leak into the output as pairs like [13, 12]. Also, using while i <= len(firstList) reads past the end, so keep the strict < for both pointers.

Edge cases

  • Either list empty, such as firstList = [[1,3],[5,9]] and secondList = []. The output is [], and the loop never reads an element.
  • Both lists empty is not allowed by the constraints, but a single empty list still returns [] as shown above.
  • Intervals that touch at one point, such as [[1,5]] and [[5,8]]. The output is [[5,5]], because closed intervals share the endpoint 5.
  • No overlap at all, such as [[1,2]] and [[3,4]]. The output is [], since the overlap start 3 is greater than the overlap end 2.
  • One long interval covering several short ones, such as [[0,10]] and [[1,2],[3,4],[5,6]]. The output is [[1,2],[3,4],[5,6]], and the long interval stays active across all three.
  • Maximum values, such as [[0,1000000000]] and [[999999999,1000000000]]. The output is [[999999999,1000000000]], and every value fits in a 32-bit signed int.

Follow-ups interviewers ask

What if the intervals inside one list can overlap each other?
The discard rule depends on disjoint intervals inside each list, so the sweep is no longer safe as written. First sort each list by start and merge any interval that starts before the running end. Sorting costs O(n log n + m log m), and after merging, the same two-pointer sweep runs in linear time.
What if the two lists arrive as streams that you cannot index?
The sweep only needs the current interval from each list, so it can read each stream one interval at a time. Each intersection can be written out as soon as it is found. Memory stays O(1) beyond whatever the caller chooses to keep.
Can you beat O(n + m) in the general case?
No. An interval that is never read could change the answer, so every algorithm must read all n + m intervals at least once. The output can also hold up to n + m - 1 intervals, so writing it takes about that many steps as well.

Interval List Intersections FAQ

What is the time complexity of Interval List Intersections?

The two-pointer solution runs in O(n + m) time, where n and m are the lengths of the two lists. Each step moves one pointer forward, so there are at most n + m steps. The brute force version takes O(n * m) time.

Why use two pointers for Interval List Intersections?

Both lists are sorted and disjoint, so only the current interval from each list can overlap the sweep at any moment. Two pointers track that pair and only move forward. This turns an n * m pair search into a single pass.

Can Interval List Intersections be solved in O(1) extra space?

Yes. The two-pointer version keeps two indices and a few temporary values. The output list is not counted as extra space, and it can hold up to n + m - 1 intervals.

Does the output include single points like [5, 5]?

Yes. The intervals are closed, so a shared endpoint is a real intersection. Example 1 includes [5,5], [24,24] and [25,25]. The overlap test must use lo <= hi.

Is the result already sorted?

Yes. Each intersection starts after the previous one ends, because the intervals inside each list are disjoint and sorted. The sweep therefore never needs a final sort.

Asked at

See which companies ask this — Pro

Practise it