Find Intersections Between Two Interval Lists
NuroSoftware Engineer · Technical ScreenLast updated
This problem tests your ability to efficiently merge and find overlaps between two sorted interval lists using a two-pointer approach.
Problem Statement
You are given two lists of closed intervals, listA and listB, where each interval is represented as [start, end]. In both lists, intervals are disjoint and sorted in ascending order by their start times.
Your task is to compute the intersection of these two interval lists. An intersection exists if there is at least one point common to an interval from listA and an interval from listB. Since both lists contain closed intervals, the intersection of [a1, a2] and [b1, b2] is [max(a1, b1), min(a2, b2)], provided that max(a1, b1) <= min(a2, b2).
Implement the function find_intersections(listA, listB):
def find_intersections(listA, listB):
# listA and listB are lists of lists, e.g., [[0, 2], [5, 10]]
pass
Examples
Example 1:
Input: listA = [[0, 2], [5, 10]], listB = [[1, 5], [8, 12]]
Output: [[1, 2], [5, 5], [8, 10]]
Explanation: The interval [1, 2] is the intersection of [0, 2] and [1, 5]. [5, 5] is the intersection of [5, 10] and [1, 5]. [8, 10] is the intersection of [5, 10] and [8, 12].
Example 2:
Input: listA = [[1, 3], [5, 9]], listB = []
Output: []
Constraints
0 <= len(listA), len(listB) <= 10^5start <= endfor all intervals.- The lists are sorted and intervals within a single list are disjoint.
Edge Cases
- Empty lists should return an empty list.
- Intervals that touch at a single point (e.g., [1, 2] and [2, 3]) should result in an intersection of [2, 2].
Hints
Hint 1
Use two pointers, `i` and `j`, to iterate through `listA` and `listB` respectively.
Hint 2
For any two intervals `A[i]` and `B[j]`, the intersection start is `max(A[i][0], B[j][0])` and the end is `min(A[i][1], B[j][1])`.
Hint 3
After processing the interval that ends earlier, increment the pointer for the list containing that interval to move forward.
Follow-up questions
- What is the time and space complexity of your solution?
- How would your approach change if the input lists were not sorted?
- If the input lists could contain overlapping intervals within themselves, how would you pre-process them before finding intersections?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.