Interval List Intersections - Problem
Find Interval List Intersections
You're given two lists of closed intervals that are already sorted and non-overlapping within each list. Your task is to find all the intersections between intervals from the two lists.
๐ฏ Goal: Return a list of all intersection intervals.
What's an intersection? Two intervals
โข
โข
Input: Two arrays of intervals
Output: Array of intersection intervals in sorted order
You're given two lists of closed intervals that are already sorted and non-overlapping within each list. Your task is to find all the intersections between intervals from the two lists.
๐ฏ Goal: Return a list of all intersection intervals.
What's an intersection? Two intervals
[a, b] and [c, d] intersect if they share any common points. For example:โข
[1, 3] and [2, 4] intersect at [2, 3]โข
[1, 2] and [3, 4] don't intersectInput: Two arrays of intervals
firstList and secondListOutput: Array of intersection intervals in sorted order
Input & Output
example_1.py โ Basic Intersection
$
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]]
๐ก Note:
Each intersection is calculated as [max(start1, start2), min(end1, end2)]. For example, [0,2] and [1,5] intersect at [1,2], [5,10] and [1,5] intersect at [5,5] (a single point), and so on.
example_2.py โ No Intersections
$
Input:
firstList = [[1,3],[5,9]], secondList = [[4,4],[10,12]]
โบ
Output:
[]
๐ก Note:
No intervals from the first list overlap with any intervals from the second list. [1,3] ends before [4,4] starts, [5,9] ends before [10,12] starts.
example_3.py โ Empty Lists
$
Input:
firstList = [], secondList = [[1,3],[5,7]]
โบ
Output:
[]
๐ก Note:
When one list is empty, there can be no intersections, so we return an empty array.
Visualization
Tap to expand
Understanding the Visualization
1
Set Up Timeline
Place both schedules on the same timeline, maintaining chronological order
2
Compare Current Meetings
Look at the current meeting from each schedule
3
Find Overlap
Calculate intersection: latest start time to earliest end time
4
Move to Next
Advance to the next meeting for whichever executive finishes earlier
Key Takeaway
๐ฏ Key Insight: Two pointers work perfectly here because both lists are pre-sorted, allowing us to process intervals chronologically without backtracking.
Time & Space Complexity
Time Complexity
O(m + n)
We traverse each list at most once, visiting each interval exactly once
โ Linear Growth
Space Complexity
O(k)
Only space for result array, where k is number of intersections
โ Linear Space
Constraints
- 0 โค firstList.length, secondList.length โค 1000
- firstList.length + secondList.length โฅ 1
- 0 โค starti < endi โค 109
- Both lists are sorted in non-decreasing order
- Intervals within each list are disjoint (non-overlapping)
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code