You are given an array of non-overlapping intervals intervals
where intervals[i] = [start_i, end_i]
, representing the start and the end of the i-th
interval, and intervals
is sorted in ascending order by start_i
. You are also given an interval newInterval = [start, end]
that represents the new interval to be inserted into intervals
.
Insert newInterval
into intervals
such that the intervals still remain non-overlapping and sorted in ascending order by start time.
Return the resulting array of intervals after the insertion.
Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]
Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Input: intervals = [], newInterval = [5,7]
Output: [[5,7]]
newInterval
starts to the result list.newInterval
. This can be done by updating newInterval
to the minimum start and maximum end of the overlapping intervals.newInterval
to the result.The time complexity of this approach is (O(n)), where (n) is the number of intervals in the input list. This is because each interval is processed at most twice – once to check for non-overlapping periods and once to either merge or append to the result list.
import java.util.ArrayList;
import java.util.List;
public class InsertInterval {
public int[][] insert(int[][] intervals, int[] newInterval) {
List<int[]> result = new ArrayList<>();
int i = 0;
int n = intervals.length;
// Add all intervals ending before newInterval starts
while (i < n && intervals[i][1] < newInterval[0]) {
result.add(intervals[i]);
i++;
}
// Merge all overlapping intervals with newInterval
while (i < n && intervals[i][0] <= newInterval[1]) {
newInterval[0] = Math.min(newInterval[0], intervals[i][0]);
newInterval[1] = Math.max(newInterval[1], intervals[i][1]);
i++;
}
result.add(newInterval);
// Add all intervals starting after newInterval ends
while (i < n) {
result.add(intervals[i]);
i++;
}
return result.toArray(new int[result.size()][]);
}
}
This code should successfully merge any newInterval
into the existing sorted, non-overlapping intervals.
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?