Leetcode#57. Insert Interval
You are given an array of non-overlapping intervals intervals
where intervals[i] = [starti, endi]
represent the start and the end of the ith
interval and intervals
is sorted in ascending order by starti
. You are also given an interval newInterval = [start, end]
that represents the start and end of another interval.
Insert newInterval
into intervals
such that intervals
is still sorted in ascending order by starti
and intervals
still does not have any overlapping intervals (merge overlapping intervals if necessary).
Return intervals
after the insertion.
Example 1:
Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]
Solution
Let’s understand it by 5 scenarios:
You can see that if curr_interval is before new_interval we can push curr_interval.
If curr_interval is after new_interval then we can insert new_interval and then can insert curr_interval.
If curr_interval and new_interval both are overlapping then we use start = min(curr_interval[start], new_interval[start]) and end = max(curr_interval[end], new_interval[end]).
Let’s see the code now:
class Solution {
public int[][] insert(int[][] intervals, int[] newInterval) {
int n = intervals.length;
List<int[]> res = new ArrayList();
boolean intervalInserted = false;
for(int i=0;i<n;i++) {
if(intervals[i][1] < newInterval[0]) {
res.add(intervals[i]);
} else if(intervals[i][0] > newInterval[1]) {
if(!intervalInserted) {
res.add(newInterval);
intervalInserted = true;
}
res.add(intervals[i]);
} else {
newInterval[0] = Math.min(newInterval[0], intervals[i][0]);
newInterval[1] = Math.max(newInterval[1], intervals[i][1]);
}
}
if(!intervalInserted) {
res.add(newInterval);
}
return res.toArray(new int[0][]); // convert to 2D array
}
}
Time Complexity: O(n)
Space Complexity: O(n)
If you really like this post, upvote it and follow me. I am on the mission of delivering explanations for GFG Problem of the Day and the Leetcode Daily Challenge.