Insert Interval (LeetCode 57): Solution and Explanation
You have a list of non-overlapping intervals sorted by start, and one new interval. Insert the new interval so the list stays sorted and non-overlapping, merging it with any intervals it touches.
Watch it run step by step
Try your own input and write the code →Intuition
A simple approach is to append the new interval, sort everything again, and run the standard merge intervals routine. That is correct and costs O(n log n), but it throws away the fact that the list is already sorted and already free of overlaps.
Because of that ordering, every existing interval falls into exactly one of three groups relative to the new one. Some end before the new interval starts, so they belong untouched on the left. Some start after the new interval ends, so they belong untouched on the right. The rest overlap the new interval, and those all collapse into one merged interval whose start is the smallest start and whose end is the largest end.
The groups appear in order: first all the left ones, then the overlapping ones, then the right ones. So one pass works. Copy intervals that are entirely to the left, absorb overlapping intervals into a growing newInterval, and as soon as you meet an interval entirely to the right, emit the merged interval followed by everything remaining. If you reach the end without ever hitting that case, the merged interval goes last.
Notice that the merged interval is only finished once you see an interval that starts strictly after its end, or once the list runs out. Until then it keeps growing, because a later interval might still overlap the expanded range. That is why the code reassigns newInterval instead of appending it during the overlap case.
Approach: Single linear pass with merging
- Start an empty result list
res. - For each interval, if
newInterval[1] < intervals[i][0], the new interval ends before this one starts. AppendnewIntervaland returnresplus the rest of the list. - Otherwise, if
newInterval[0] > intervals[i][1], this interval ends before the new one starts, so append it unchanged. - Otherwise they overlap, so replace
newIntervalwith the min of the starts and the max of the ends. - If the loop finishes, append the merged
newIntervalat the end and returnres.
Step-by-step example
intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
- [1,2]: the new start 4 is greater than 2, so [1,2] goes into
resunchanged. - [3,5]: neither rule applies, so they overlap.
newIntervalbecomes [3,8]. - [6,7]: overlaps [3,8].
newIntervalstays [3,8]. - [8,10]: 8 is not less than 8 and 3 is not greater than 10, so they overlap (touching counts).
newIntervalbecomes [3,10]. - [12,16]: 10 < 12, so append [3,10] and return it with the remainder: [[1,2],[3,10],[12,16]].
Code: Python, Java, C++
1class Solution:
2 def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
3 res = []
4
5 for i in range(len(intervals)):
6 if newInterval[1] < intervals[i][0]:
7 res.append(newInterval)
8 return res + intervals[i:]
9 elif newInterval[0] > intervals[i][1]:
10 res.append(intervals[i])
11 else:
12 newInterval = [
13 min(newInterval[0], intervals[i][0]),
14 max(newInterval[1], intervals[i][1])
15 ]
16 res.append(newInterval)
17 return res1class Solution {
2 public int[][] insert(int[][] intervals, int[] newInterval) {
3 List<int[]> res = new ArrayList<>();
4 int i = 0;
5 int n = intervals.length;
6
7 while (i < n && intervals[i][1] < newInterval[0]) {
8 res.add(intervals[i]);
9 i++;
10 }
11
12 while (i < n && intervals[i][0] <= newInterval[1]) {
13 newInterval[0] = Math.min(newInterval[0], intervals[i][0]);
14 newInterval[1] = Math.max(newInterval[1], intervals[i][1]);
15 i++;
16 }
17 res.add(newInterval);
18
19 while (i < n) {
20 res.add(intervals[i]);
21 i++;
22 }
23
24 return res.toArray(new int[res.size()][]);
25 }
26}1class Solution {
2public:
3 vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
4 vector<vector<int>> res;
5 int i = 0;
6 int n = intervals.size();
7
8 while (i < n && intervals[i][1] < newInterval[0]) {
9 res.push_back(intervals[i]);
10 i++;
11 }
12
13 while (i < n && intervals[i][0] <= newInterval[1]) {
14 newInterval[0] = min(newInterval[0], intervals[i][0]);
15 newInterval[1] = max(newInterval[1], intervals[i][1]);
16 i++;
17 }
18 res.push_back(newInterval);
19
20 while (i < n) {
21 res.push_back(intervals[i]);
22 i++;
23 }
24
25 return res;
26 }
27};Time and space complexity
O(n)
Each existing interval is examined once, and the final slice copies the remaining intervals in linear time.
O(n)
The result list can hold up to n + 1 intervals. Apart from the output, only constant extra space is used.
Other approaches
Append, sort and merge (time O(n log n), space O(n))
Add the new interval to the list, sort by start, and apply the merge intervals algorithm. It reuses familiar code but pays for a sort the input did not need.
Binary search for the boundaries (time O(n), space O(n))
Use binary search to find the first interval that could overlap and the last one, then splice in a single merged interval. Finding the range is O(log n), but building the output list is still linear.
Common mistakes
- Using
<=in the left and right checks, which treats touching intervals such as [1,5] and [5,7] as separate when they should merge. - Forgetting to append
newIntervalafter the loop, which drops it whenever it belongs at the very end or absorbs the last interval. - Appending
newIntervalat the moment of overlap instead of continuing to grow it, which leaves several pieces that still overlap. - Not handling an empty input list. The loop simply does not run and the code appends the new interval, which is correct.
Frequently asked questions
How is insert interval different from merge intervals?
Merge intervals starts from an unsorted list and needs an O(n log n) sort. Here the list is already sorted and non-overlapping, so a single O(n) pass is enough to place and merge the new interval.
Do touching intervals count as overlapping?
Yes. Intervals like [3,8] and [8,10] share the point 8, so they merge into [3,10]. The strict comparisons in the left and right checks make that happen.
Can insert interval be done in place?
You can modify the original list, but removing the merged range still shifts elements, so the time stays linear. Returning a new list is simpler and has the same complexity.