Untitled

 avatar
unknown
plain_text
21 days ago
1.2 kB
2
Indexable
class Solution {
    public int[][] intervalIntersection(int[][] firstList, int[][] secondList) {
        // If either list is empty, return empty list
        if (firstList.length == 0 || secondList.length == 0) {
            return new int[0][];
        }
        
        List<int[]> result = new ArrayList<>();
        int i = 0, j = 0;
        
        // Iterate through both lists
        while (i < firstList.length && j < secondList.length) {
            // Find the intersection start and end
            int start = Math.max(firstList[i][0], secondList[j][0]);
            int end = Math.min(firstList[i][1], secondList[j][1]);
            
            // If valid intersection, add to result
            if (start <= end) {
                result.add(new int[]{start, end});
            }
            
            // Move the pointer of the interval that ends earlier
            if (firstList[i][1] < secondList[j][1]) {
                i++;
            } else {
                j++;
            }
        }
        
        // Convert list to 2D array
        return result.toArray(new int[result.size()][]);
    }
}
Leave a Comment