Problem Description
Given two lists of disjoint intervals sorted by starting times, firstList and secondList, the task is to find their intersections. An intersection of two intervals is defined as a closed interval where the intervals overlap. Return a list of all such intersections.
Key Insights
- Use two pointers to traverse both lists simultaneously.
- Determine the overlapping interval by taking the maximum of the start points and the minimum of the end points.
- If the overlapping condition (start <= end) is met, add the intersection to the result.
- Move the pointer that has the smaller end value to explore further potential intersections efficiently.
- Achieve an overall time complexity of O(m+n), where m and n are the lengths of the two interval lists.
Space and Time Complexity
Time Complexity: O(m + n) where m and n are the lengths of firstList and secondList respectively. Space Complexity: O(1) extra space (excluding the space used for the output).
Solution
The solution uses a two pointers approach. Initialize two indices, one for each list, and iterate through both lists. For each pair of intervals, the potential intersection is computed by:
- Calculating the maximum of the two start values.
- Calculating the minimum of the two end values. If the maximum start is less than or equal to the minimum end, there is an intersection, and it is added to the result list. The pointer corresponding to the interval with the smaller end value is then incremented since that interval cannot intersect with any further intervals from the other list. This process repeats until one of the lists is fully traversed.