You are given an array of intervals where intervals[i] = [start_i, end_i]
, merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
import java.util.*;
public class MergeIntervals {
public static int[][] merge(int[][] intervals) {
if (intervals.length <= 1) {
return intervals; // If there is 0 or 1 interval, return it as is.
}
// Sort intervals based on the start time
Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
List<int[]> merged = new ArrayList<>();
int[] currentInterval = intervals[0];
merged.add(currentInterval);
for (int[] interval : intervals) {
int currentEnd = currentInterval[1];
int nextStart = interval[0];
int nextEnd = interval[1];
// Check for overlap
if (currentEnd >= nextStart) {
// Merge intervals
currentInterval[1] = Math.max(currentEnd, nextEnd);
} else {
// No overlap, add the interval to the list
currentInterval = interval;
merged.add(currentInterval);
}
}
return merged.toArray(new int[merged.size()][]);
}
public static void main(String[] args) {
int[][] intervals = // use example from above
System.out.println(Arrays.deepToString(merge(intervals))); // [[1, 6], [8, 10], [15, 18]]
intervals = new int[][]// use example from above
System.out.println(Arrays.deepToString(merge(intervals))); // [[1, 5]]
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?