Sponsored
Sponsored
In this approach, we use a two-pointer technique to traverse both lists of intervals simultaneously. We check for intersections between the intervals pointed by our two pointers. If there's an intersection, we record it. We then progress the pointer that points to the interval with the smaller endpoint. This ensures that we consider new overlapping possibilities as the intervals in each list are disjoint and sorted.
Time Complexity: O(n + m), where n and m are the number of intervals in the two lists. This is because we process each interval at most once.
Space Complexity: O(1), apart from the output space, since only a few variables are used.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public int[][] IntervalIntersection(int[][] firstList, int[][] secondList) {
6 List<int[]> result = new List<int[]>();
7 int i = 0, j = 0;
8 while (i < firstList.Length && j < secondList.Length) {
9 int start = Math.Max(firstList[i][0], secondList[j][0]);
10 int end = Math.Min(firstList[i][1], secondList[j][1]);
11 if (start <= end) {
12 result.Add(new int[] {start, end});
13 }
14 if (firstList[i][1] < secondList[j][1])
15 i++;
16 else
17 j++;
18 }
19 return result.ToArray();
20 }
21}
By utilizing two pointers i
and j
, the method checks for intersection intervals and moves pointers based on their endpoint comparison. This method ensures every pair is checked efficiently.