57. Insert Interval#

Given a sorted array of non-overlapping intervals (intervals) and a new interval (newInterval), insert newInterval into intervals while maintaining sorted order and merging overlapping intervals if necessary.

Example

Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Explanation: The new interval [4,8] overlaps with [3,5],[6,7],[8,10]

Approach#

When comparing two intervals P and Q it can be:

  1. P can come before Q.

  2. Q can come before P.

  3. P and Q can be overlapped then, merge by taking MIN of start and MAX of end.

Loop over intervals and compare new and current and add or merge accordingly.

Code#

 1public int[][] insert(int[][] intervals, int[] newInterval) {
 2  List<int[]> list = new ArrayList<>();
 3  boolean inserted = false;
 4
 5  for (int[] currentInterval : intervals) {
 6    if (inserted || currentInterval[1] < newInterval[0]) {
 7      // when current interval is before new interval
 8      list.add(currentInterval);
 9    } else if (newInterval[1] < currentInterval[0]) {
10      // when new interval is before current interval
11      list.add(newInterval);
12      inserted = true;
13
14      list.add(currentInterval);
15    } else {
16      // when overlapping exists
17      newInterval[0] = Math.min(newInterval[0], currentInterval[0]);
18      newInterval[1] = Math.max(newInterval[1], currentInterval[1]);
19    }
20  }
21
22  if (!inserted) {
23    list.add(newInterval);
24  }
25
26  return list.toArray(new int[list.size()][]);
27}

Time Complexity

Space Complexity

\(\mathcal{O}(n)\)

\(\mathcal{O}(n)\)