Start learning free

LESSON 554 OF 673 · INTERVALS

Interval List Intersections in Python: O(m + n) Two Pointers

Practice O(m + n) Read the full explanation

You get two lists of intervals, first and second. Each interval is a pair [start, end]. It covers every point from its start to its end.

Return a list of the overlaps between the two lists, from left to right. An overlap is the part that an interval of first shares with an interval of second.

Each list is sorted by start. Inside one list, no two intervals overlap or touch.

Two intervals that only touch share one point. For example, [1,4] and [4,6] overlap in [4,4].

 

Example 1:

Input: first = [[2,6],[9,12]], second = [[4,10]]
Output: [[4,6],[9,10]]
Explanation: [4,10] overlaps both intervals of first.
It shares 4 to 6 with [2,6].
It shares 9 to 10 with [9,12].

Example 2:

Input: first = [[0,3],[8,15]], second = [[3,5],[9,10],[12,12]]
Output: [[3,3],[9,10],[12,12]]
Explanation: [0,3] and [3,5] touch at 3.
[9,10] and [12,12] lie inside [8,15].
They overlap it in full.

Example 3:

Input: first = [[1,2],[7,8]], second = [[4,5]]
Output: []
Explanation: [4,5] sits in the gap between [1,2] and [7,8].
No point is in both.

 

Constraints:

  • first holds m intervals, from 0 to 100,000.
  • second holds n intervals, from 0 to 100,000.
  • Each start and end is a whole number from 0 to 1,000,000,000.
  • No start is greater than its end.
  • In each list, an interval ends before the next one starts.

Note:

Your solution should run in O(m + n) time.

STEP 1 OF 9
    Ctrl + Enter to check

    PYTHON · INTERVALS

    Interval List Intersections in Python, explained

    Problem overview

    The method intervalIntersection receives two lists of intervals, first and second. Each interval is a pair [start, end] that covers every point from its start to its end. Each list is sorted by start, and inside one list no two intervals overlap or touch. The method returns the list of overlaps between the two lists, from left to right. An overlap is the part that an interval of first shares with an interval of second.

    Intervals that only touch share one point, so [1, 4] and [4, 6] overlap in [4, 4].

    With first = [[2, 6], [9, 12]] and second = [[4, 10]] the answer is [[4, 6], [9, 10]]: the interval [4, 10] shares 4 to 6 with [2, 6] and 9 to 10 with [9, 12]. With first = [[1, 2], [7, 8]] and second = [[4, 5]] the answer is [], because [4, 5] sits in the gap between the two.

    The lesson asks for O(m + n) time, for lists of m and n intervals. Either list may be empty.

    Approach: two pointers, drop the interval that ends first

    Comparing every interval of one list with every interval of the other costs O(m · n), with up to 100,000 intervals in each list. The sorting of both lists makes that unnecessary.

    Keep one pointer in each list, i in first and j in second. Look at first[i] and second[j]:

    • Their overlap, if any, starts at the later of the two starts and ends at the earlier of the two ends.
    • If that start is at most that end, the overlap is real. If the start is larger, the intervals share no point.

    Then one of the two pointers has to move. The interval that ends first can't overlap anything later in the other list, because every later interval of the other list starts after the current one ends. That interval is finished, so its pointer moves forward. The other interval stays, since it reaches further right and may still overlap the next interval of the first list.

    Each turn moves a pointer by one, so the loop runs at most m + n times.

    Step by step

    1. Create result = [], which collects the overlaps. Its length isn't known in advance.
    2. Set i, j = 0, 0 in one line. These are the pointers.
    3. Loop while i < len(first) and j < len(second). Once either list runs out, nothing is left to overlap.
    4. Compute start as max(first[i][0], second[j][0]). Before the larger start, one of the two intervals has not begun.
    5. Compute end as min(first[i][1], second[j][1]). After the smaller end, one of the two is over.
    6. If start <= end, append [start, end] to result. Equal values count: the intervals touch in one point.
    7. If first[i][1] < second[j][1], add 1 to i: the interval of first ends first.
    8. Else add 1 to j. Here the interval of second ends first, or both end together. When both end at the same point, moving j is enough, because the next turn finds no overlap and moves i.
    9. Return result.

    Take first = [[0, 3], [8, 15]] and second = [[3, 5], [9, 10], [12, 12]]. Each line shows i, j, the two intervals, and the start and end computed:

    0 0 [0, 3] [3, 5] 3 3
    1 0 [8, 15] [3, 5] 8 5
    1 1 [8, 15] [9, 10] 9 10
    1 2 [8, 15] [12, 12] 12 12

    Turn one: start 3 and end 3 make an overlap [3, 3]. Then [0, 3] ends first, so i moves. Turn two: start 8 is greater than end 5, so there is no overlap, and [3, 5] ends first, so j moves. Turns three and four give [9, 10] and [12, 12]. The result is [[3, 3], [9, 10], [12, 12]].

    The solution in Python

    class Solution:
        def intervalIntersection(self, first: List[List[int]], second: List[List[int]]) -> List[List[int]]:
            result = []
            i, j = 0, 0
            while i < len(first) and j < len(second):
                start = max(first[i][0], second[j][0])
                end = min(first[i][1], second[j][1])
                if start <= end:
                    result.append([start, end])
                if first[i][1] < second[j][1]:
                    i += 1
                else:
                    j += 1
            return result
    

    Python details:

    • i, j = 0, 0 is tuple unpacking: both names get their value in one line.
    • Each interval is a two-element list, so first[i][0] is its start and first[i][1] its end.
    • The result holds new lists, [start, end], rather than the input intervals, so the inputs are left unchanged.

    Complexity

    Time: O(m + n). Every turn of the loop advances i or j, and neither moves back, so there are at most m + n turns, each with constant work.

    Space: O(1) besides the answer. Only the two pointers and two numbers are stored. The result list holds at most m + n overlaps.

    Edge cases and common mistakes

    • An empty list. If either list is empty, the loop condition is false at once and the method returns [].
    • Touching intervals. [[1, 4]] and [[4, 6]] give [[4, 4]]. Using start < end would lose these one-point overlaps.
    • Moving both pointers every turn. That can skip an overlap: a long interval may overlap several intervals of the other list, as [4, 10] does in the first example.
    • Moving the pointer of the interval that ends later. The one that ends first must go. The later one may still overlap the next interval of the other list.
    • Appending without the check. When start is larger than end, the pair is not an interval at all.

    Testing

    Results from running the method:

    firstsecondResult
    [[2, 6], [9, 12]][[4, 10]][[4, 6], [9, 10]]
    [[0, 3], [8, 15]][[3, 5], [9, 10], [12, 12]][[3, 3], [9, 10], [12, 12]]
    [[1, 2], [7, 8]][[4, 5]][]
    [][[1, 2]][]
    [[1, 4]][[4, 6]][[4, 4]]
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free