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()
Difficulty
and has an acceptance rate of about 73% (800k+ submissions).
Typical patterns to solve this problem:
- Array
- Sweep Line
- Two Pointers
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 88: Merge Sorted Array
Solved On The Same Day
- problem 1260: Shift 2D Grid
- problem 1309: Decrypt String from Alphabet to Integer Mapping
- problem 2520: Count the Digits That Divide a Number
- problem 2553: Separate the Digits in an Array
- problem 2815: Max Pair Sum in an Array
- problem 2833: Furthest Point From Origin
- problem 921: Minimum Add to Make Parentheses Valid
- problem 1003: Check If Word Is Valid After Substitutions
- problem 564: Find the Closest Palindrome
Extra
- 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