Problem Statement

Pattern: Related: 435. Non-Overlapping Intervals, 252 Meeting Rooms 253 Meeting Rooms II
Solution
public int[][] merge (int[][] intervals){
// Sort by interval start
Arrays.sort(intervals, Comparator.comparingInt(a -> a[0]));
ArrayList<int[]> res = new ArrayList<>();
int[] currInterval = intervals[0];
for(int[] newInterval: intervals) {
if(newInterval[0] <= currInterval[1])
// extend the end of the currInterval
currInterval[1] = Math.max(currInterval[1], newInterval[1]);
else {
res.add(currInterval);
// set newInterval as the currInterval
currInterval = newInterval;
}
}
res.add(currInterval); // add the final currInterval
return res.toArray(new int[0][]);
}Notes
- iterate through all intervals
- keep the
currIntervalto compare with thenewInterval - if they overlap, extend the
currInterval(update the end ofcurrIntervaltomax(currInterval[1], newInterval[])) - once
currIntervalstops overlapping withnewInterval, we add the now (extended )currentIntervaltoresarraylist
- keep the
- finally the last
newIntervalwhich is either extended in theifcondition to thecurrIntervalor is unique so gets set tocurrIntervalin the else block. either ways the finalnewIntervalends up incurrIntervalso we addcurrIntervalto result