Interval List Intersections — LeetCode 986 Python Solution

MediumArrayTwo PointersLine Sweep
Problem
#986
Reading time
3 min

The problem

You are given two lists of closed intervals, firstList and secondList, where firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Each list of intervals is pairwise disjoint and in sorted order.

Example

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

Python solution

Python
class Solution:
    def intervalIntersection(
        self, firstList: List[List[int]], secondList: List[List[int]]
    ) -> List[List[int]]:
        i = j = 0
        ans = []
        while i < len(firstList) and j < len(secondList):
            s1, e1, s2, e2 = *firstList[i], *secondList[j]
            l, r = max(s1, s2), min(e1, e2)
            if l <= r:
                ans.append([l, r])
            if e1 < e2:
                i += 1
            else:
                j += 1
        return ans

Complexity

MeasureComplexity
TimeO(n) (after optional sort O(n log n))
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 986. Interval List Intersections is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 986. Interval List Intersections?
LeetCode 986. Interval List Intersections is rated Medium on LeetCode.
What is the time complexity of LeetCode 986. Interval List Intersections?
The Python solution on this page runs in O(n) (after optional sort O(n log n)).
What is the space complexity of LeetCode 986. Interval List Intersections?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 986. Interval List Intersections cover?
LeetCode 986. Interval List Intersections is tagged Array, Two Pointers and Line Sweep on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview