In this problem, we are given 2 sets of various pairs of numbers. Each pair in each set is an interval. We are asked to find the intersections/overlaps of the two sets.
// What we need to do here is simply find the overlapping times between two sets of times we then repeat it for every element. First we create a list to store all the time intervals that we determine to be overlappingclass Solution {
public int[][] intervalIntersection(int[][] A, int[][] B) {
List<int[] > list = new ArrayList<>();
for( int a = 0, b = 0; a < A.length && b < B.length; ){
// Find out which starts later
int start = Math.max(A[a][0],B[b][0]);
// Find out which ends earlier
int end = Math.min(A[a][1],B[b][1]); // Since start is less than or equal to end, this means
over lap exists
if( start <= end ) list.add(new int[] {start,end});
// This checks if we need to move to next element on the A list or the B list if the end of A is less than end of B then we no longer need to check for that A element because the array is sorted .. else we move on to next element.
if (A[a][1] < B[b][1]){
a++;
} else{
b++;
}
}
return list.toArray(new int[list.size()][]);
}
}
Video:
Thank you!