Intuition
Add the new interval to the list, sort everything, then merge overlapping intervals just like the Merge Intervals problem.
Explanation
Brute Force
Append newInterval to the end of intervals, sort the combined list by start time, then sweep through and merge any overlapping pairs.
Sorting costs O(n log n) even though the input was already sorted. Space is O(n) for the output.
Why it is slow: We throw away the fact that intervals is already sorted and re-sort the entire list.
Implementation
import java.util.*;
class Solution {
public int[][] insert(int[][] intervals, int[] newInterval) {
List<int[]> all = new ArrayList<>(Arrays.asList(intervals));
all.add(newInterval);
all.sort((a, b) -> a[0] - b[0]);
List<int[]> merged = new ArrayList<>();
merged.add(all.get(0));
for (int i = 1; i < all.size(); i++) {
int[] last = merged.get(merged.size() - 1);
if (all.get(i)[0] <= last[1]) {
last[1] = Math.max(last[1], all.get(i)[1]);
} else {
merged.add(all.get(i));
}
}
return merged.toArray(new int[0][]);
}
}