MrainW's Home

All things come to those who wait!

0%

LeetCode 57. Insert Interval

Question

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.

https://leetcode.com/problems/insert-interval/

  • Solution1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int[][] insert(int[][] intervals, int[] newInterval) {
List<int[]> res = new ArrayList<>();
for (int[] cur : intervals)
if (newInterval == null || cur[1] < newInterval[0]) res.add(cur);
else if (cur[0] > newInterval[1]){
res.addAll(List.of(newInterval, cur));
newInterval = null;
} else {
newInterval[0] = Math.min(newInterval[0], cur[0]);
newInterval[1] = Math.max(newInterval[1], cur[1]);
}
if (newInterval != null) res.add(newInterval);
return res.toArray(new int[res.size()][]);
}
}

Complexity:

Time complexity: O( n)

Space complexity: O(n)

Welcome to my other publishing channels