Problem 986

Abstract / Summary

Given two lists of intervals, find all overlapping intervals between them.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0986.py

class Solution:
    def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:
        # popping from the end is much faster than from the beginning
        firstList  = list(reversed(firstList))
        secondList = list(reversed(secondList))
        while firstList and secondList:
            f1, f2 = firstList[-1]
            s1, s2 = secondList[-1]
            # remove uncrossed intervals
            if f2 < s1:
                firstList.pop()
                continue
            if s2 < f1:
                secondList.pop()
                continue

            # intersection
            i1 = max(f1, s1)
            i2 = min(f2, s2)
            yield i1, i2

            # remove if intersection completed "used" that interval
            if f2 <= i2:
                firstList .pop()
            if s2 <= i2:
                secondList.pop()
26 lines | 930 bytes | submitted December 21, 2023 | GitHub   20% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 73% (800k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Sweep Line
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The intervalIntersection method receives two sorted collections of closed intervals and produces the list of all overlapping sub-intervals. By converting the input lists into reversed stacks, the algorithm can repeatedly examine the last elements, decide whether they intersect, emit the intersection, and discard intervals that have been fully processed. The use of a generator (yield) allows the caller to consume results incrementally without building an intermediate collection.

Key Steps

The first operation creates stack-like structures by reversing the original lists. This transformation enables constant-time removal from the end, which is faster than removing from the front of a Python list.

firstList  = list(reversed(firstList))
secondList = list(reversed(secondList))

A loop runs while both stacks contain elements. In each iteration the current intervals are taken from the top of each stack.

while firstList and secondList:
    f1, f2 = firstList[-1]
    s1, s2 = secondList[-1]

The algorithm discards intervals that cannot possibly intersect the opposite interval. If the end of the first interval is before the start of the second, the first interval is popped; the symmetric case applies to the second interval.

if f2 < s1:
    firstList.pop()
    continue
if s2 < f1:
    secondList.pop()
    continue

When the intervals overlap, the intersection boundaries are computed with max for the left edge and min for the right edge. The pair is emitted via yield.

i1 = max(f1, s1)
i2 = min(f2, s2)
yield i1, i2

Finally, any interval that has been exhausted by the intersection is removed from its stack. An interval is considered exhausted when its right endpoint is less than or equal to the right endpoint of the produced intersection.

if f2 <= i2:
    firstList.pop()
if s2 <= i2:
    secondList.pop()

Edge Cases Handled

When either input list is empty, the initial while condition fails immediately, and the generator produces no output, correctly representing the absence of intersections. Intervals that touch at a single point (for example [2,5] and [5,7]) satisfy f2 < s1 and s2 < f1 only when there is a strict gap; the equality case falls through to the intersection logic, yielding the single-point overlap [5,5]. Intervals where one completely contains the other are handled by the same intersection calculation, producing the smaller interval as the result and then discarding the exhausted interval while retaining the longer one for possible further overlaps. Consecutive intervals that do not overlap are removed in successive iterations without affecting the other list, ensuring that the algorithm progresses correctly even when large gaps exist between intervals.

Performance Optimizations

Reversing the input lists transforms them into stacks that support pop() from the end in amortized O(1) time, avoiding the linear cost of pop(0). The loop processes each interval at most once, and the conditional checks quickly eliminate non-overlapping intervals without additional arithmetic. By yielding each intersection as soon as it is discovered, the method avoids constructing a full result list in memory, which is advantageous when the number of intersections is large. The use of simple integer comparisons (max, min, and relational operators) keeps the inner loop lightweight, contributing to fast execution even for long input sequences.

written by openai gpt

ELI5 - Simplified Explanation

Imagine two long hallways with colored stickers on the floor. Some stickers are red and some are blue. Both rows of stickers are laid out in order. The goal is to find the places where a red sticker and a blue sticker overlap to create a purple spot.

The code starts by looking at the very beginning of both rows of stickers. It checks if the space where a red sticker sits and the space where a blue sticker sits share any ground. If the red one ends before the blue one even begins, the code decides that the red sticker is too far back, so it takes it away to check the next one. The same thing happens if the blue one is too far back.

When the two stickers finally share a space, the code finds the exact start and end of that overlap. It picks the biggest starting number and the smallest ending number to find the exact middle part where they both exist at once. This shared space represents the purple spot. After finding a purple spot, the code looks to see if one of those stickers is finished. If a sticker has been completely covered by the overlap or passed by, it gets taken away so the next part of the row can be checked. This process repeats until there are no more stickers left to compare in the hallways.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.41 | σ = 1.79

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Go Rust TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fpdjsns C++
fsq C++
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
MacJim C++
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fpdjsns C++
fsq C++
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
MacJim C++
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
38 links | 24 authors | 9 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

10 solutions   December 21, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality