15% off all plans & roadmaps Use code
See plansInsert Interval
- LeetCode 57
- Medium
- Greedy Patterns
- Interval Merging/Scheduling
Updated
TL;DR: You add one interval to a sorted list of disjoint intervals and merge whatever it touches. Because the list is already sorted, one left-to-right pass in three phases does it in O(n).
Problem
You are given an array of non-overlapping intervals intervals, where intervals[i] = [starti, endi] gives the start and end of the ith interval. The array is sorted in ascending order by starti. You are also given an interval newInterval = [start, end].
Insert newInterval into intervals so that the array stays sorted by starti and still has no overlapping intervals. Merge intervals where necessary. Return intervals after the insertion.
You do not need to modify intervals in place. You can build and return a new array.
Example 1
Input: intervals = [[1,3],[6,9]], newInterval = [2,5] Output: [[1,5],[6,9]]
Example 2
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] and [8,10], so all four merge into [3,10].
Constraints
0 <= intervals.length <= 10^4intervals[i].length == 20 <= starti <= endi <= 10^5intervalsis sorted bystartiin ascending order.newInterval.length == 20 <= start <= end <= 10^5
Constraints that matter
intervals.lengthis at most 10^4, so even O(n log n) passes easily. The real goal is to use the sorted order and reach O(n).intervalsis already sorted by start and has no overlaps. That guarantee lets you split the list into a left group, a middle group and a right group with no sorting.intervals.lengthcan be 0, so your code must handle an empty list and still return[newInterval].- Values go up to 10^5 and fit easily in a 32-bit int, so there is no overflow risk in any language.
starti <= endifor every interval, so no interval is inverted andminandmaxmerging is safe.
Hints
Hint 1
This is the interval merging pattern with a greedy sweep.
Hint 2
Ignore the fact that the list is already sorted.
Solution
Intuition
This is the interval merging pattern with a greedy sweep. The input is sorted and disjoint, so every existing interval sits in exactly one of three places relative to the new one: entirely to its left, overlapping it, or entirely to its right. Those three groups appear in that order in the list.
Picture a wall calendar of non-overlapping meetings already in order. The sticky note is your new meeting: you stretch it over every meeting it touches, then copy the untouched meetings before and after as they are.
What to notice: the list is sorted by start, and no two intervals overlap, so ends are sorted too. An interval that ends before the new one starts can never matter again. An interval that starts after the new one ends can never matter either. Only the contiguous middle block needs real work.
Why a single pass works: while you scan the middle block, you grow the new interval to cover each overlapping neighbor. Growing it takes the smaller start and the larger end. Once you reach an interval that starts after the grown interval ends, nothing further right can touch it, because later starts are even larger. You never go back.
Two intervals overlap when a.start <= b.end and b.start <= a.end. Touching at a single point counts, so [1,2] and [2,3] merge into [1,3]. The left test is therefore a strict end < newStart, and the middle test is start <= newEnd.
Worked example
Input: intervals = [], newInterval = [5, 7] Output: [[5, 7]] Explanation: The list is empty, so nothing can overlap the new interval. The answer is the new interval alone, wrapped in a list.
Approach 1: Brute force: append, sort, merge
Ignore the fact that the list is already sorted. Treat the task as the general merge-intervals problem. Add the new interval to the list, sort everything by start, then sweep once and merge any interval whose start is at most the end of the last merged one.
This is correct for any input order, which is why it is the baseline. It is also the first thing most people write.
Steps
- Copy
intervalsinto a new list and appendnewInterval. - Sort the new list by start value.
- Create an empty
resultlist. - For each interval in sorted order, check whether
resultis non-empty and its last end is at least the current start. - If so, set the last end in
resultto the larger of the two ends. Otherwise append a copy of the current interval. - Return
result.
Dry run
On intervals = [], newInterval = [5, 7]:
- The combined list is
[[5,7]]. - Sorting one element changes nothing.
resultis empty, so[5,7]is appended.- The sweep ends and the function returns
[[5,7]].
On a larger input such as [[1,3],[6,9]] plus [2,5], sorting gives [[1,3],[2,5],[6,9]]. The sweep merges [1,3] and [2,5] into [1,5], then appends [6,9].
Complexity
| Time | O(n log n) |
|---|---|
| Space | O(n) |
Here n is the number of existing intervals. The combined list has n + 1 items and sorting it costs O(n log n). The merge sweep visits each item once for O(n) extra, so sorting dominates. The sorted copy and the result list each hold at most n + 1 intervals, which gives O(n) space.
PythonTested in our runner
from typing import List, Optional
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
items = intervals + [newInterval]
items.sort(key=lambda x: x[0])
result = []
for s, e in items:
if result and result[-1][1] >= s:
# overlaps the last merged interval: extend its end
result[-1][1] = max(result[-1][1], e)
else:
result.append([s, e])
return result
JavaTested in our runner
import java.util.*;
class Solution {
public int[][] insert(int[][] intervals, int[] newInterval) {
int n = intervals.length;
int[][] items = new int[n + 1][];
for (int i = 0; i < n; i++) {
items[i] = intervals[i];
}
items[n] = newInterval;
Arrays.sort(items, (a, b) -> Integer.compare(a[0], b[0]));
List<int[]> result = new ArrayList<>();
for (int[] cur : items) {
if (!result.isEmpty() && result.get(result.size() - 1)[1] >= cur[0]) {
int[] last = result.get(result.size() - 1);
last[1] = Math.max(last[1], cur[1]);
} else {
result.add(new int[]{cur[0], cur[1]});
}
}
return result.toArray(new int[0][]);
}
}
C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
vector<vector<int>> items = intervals;
items.push_back(newInterval);
sort(items.begin(), items.end());
vector<vector<int>> result;
for (const auto& cur : items) {
if (!result.empty() && result.back()[1] >= cur[0]) {
result.back()[1] = max(result.back()[1], cur[1]);
} else {
result.push_back(cur);
}
}
return result;
}
};
JavaScriptTested in our runner
/**
* @param {number[][]} intervals
* @param {number[]} newInterval
* @return {number[][]}
*/
var insert = function(intervals, newInterval) {
const items = [...intervals, newInterval].sort((a, b) => a[0] - b[0]);
const result = [];
for (const [s, e] of items) {
if (result.length > 0 && result[result.length - 1][1] >= s) {
const last = result[result.length - 1];
last[1] = Math.max(last[1], e);
} else {
result.push([s, e]);
}
}
return result;
};
GoTested in our runner
import "sort"
func insert(intervals [][]int, newInterval []int) [][]int {
items := make([][]int, 0, len(intervals)+1)
items = append(items, intervals...)
items = append(items, newInterval)
sort.Slice(items, func(a, b int) bool {
return items[a][0] < items[b][0]
})
result := [][]int{}
for _, cur := range items {
n := len(result)
if n > 0 && result[n-1][1] >= cur[0] {
if cur[1] > result[n-1][1] {
result[n-1][1] = cur[1]
}
} else {
result = append(result, []int{cur[0], cur[1]})
}
}
return result
}
C#Tested in our runner
public class Solution {
public int[][] insert(int[][] intervals, int[] newInterval) {
List<int[]> items = new List<int[]>(intervals);
items.Add(newInterval);
items.Sort((a, b) => a[0].CompareTo(b[0]));
List<int[]> result = new List<int[]>();
foreach (int[] cur in items) {
if (result.Count > 0 && result[result.Count - 1][1] >= cur[0]) {
int[] last = result[result.Count - 1];
last[1] = Math.Max(last[1], cur[1]);
} else {
result.Add(new int[] { cur[0], cur[1] });
}
}
return result.ToArray();
}
}

Solution pattern
Interval Merging/Scheduling
Part of Greedy Patterns
Approach 2: One-pass three-phase scanOptimalInterval Merging/Scheduling
What's slow: the sort. It reorders a list that was already in order, and it costs O(n log n) to learn nothing new. The only unsorted item is the new interval, and you know where it belongs by comparing it with neighbors.
The insight that fixes it: split the scan into three phases that follow the sorted order. First copy every interval that ends before the new one starts. Then absorb every interval that starts at or before the new interval's current end, widening the new interval each time. Finally copy what is left. Each interval is touched once.
Steps
- Create
result, seti = 0, and readstartandendfromnewIntervalinto local variables. - Phase 1: while
i < nandintervals[i][1] < start, appendintervals[i]toresultand advancei. - Phase 2: while
i < nandintervals[i][0] <= end, setstart = min(start, intervals[i][0])andend = max(end, intervals[i][1]), then advancei. - Append
[start, end]toresult. - Phase 3: while
i < n, appendintervals[i]toresultand advancei. - Return
result.
Dry run
Trace on intervals = [], newInterval = [5, 7]. Here n = 0, so every loop guard i < n fails at once.
| Step | Action | i | start | end | result |
|---|---|---|---|---|---|
| 0 | Initialize, read [5,7] | 0 | 5 | 7 | [] |
| 1 | Phase 1 check: 0 < 0 is false, skip | 0 | 5 | 7 | [] |
| 2 | Phase 2 check: 0 < 0 is false, skip | 0 | 5 | 7 | [] |
| 3 | Append [start, end] | 0 | 5 | 7 | [[5,7]] |
| 4 | Phase 3 check: 0 < 0 is false, skip | 0 | 5 | 7 | [[5,7]] |
| 5 | Return | 0 | 5 | 7 | [[5,7]] |
The output is [[5,7]], which matches the expected answer.
For a case that exercises all phases, take [[1,2],[3,5],[6,7],[8,10],[12,16]] with [4,8]. Phase 1 copies [1,2] because 2 < 4. Phase 2 absorbs [3,5] (start 3, end 8), [6,7] (no change) and [8,10] (end 10), giving [3,10].
[12,16] starts at 12, which is greater than 10, so phase 2 stops. Phase 3 copies [12,16]. The result is [[1,2],[3,10],[12,16]].
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Here n is the number of existing intervals. The index i only moves forward and is shared by all three loops, so each interval is examined once and the total work is O(n). Auxiliary space beyond the output is O(1), but the returned list holds up to n + 1 intervals, so counting the output gives O(n).
PythonTested in our runner
from typing import List, Optional
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
result = []
i, n = 0, len(intervals)
start, end = newInterval[0], newInterval[1]
# Phase 1: intervals that finish before the new one starts
while i < n and intervals[i][1] < start:
result.append(intervals[i])
i += 1
# Phase 2: intervals that overlap, absorbed into [start, end]
while i < n and intervals[i][0] <= end:
start = min(start, intervals[i][0])
end = max(end, intervals[i][1])
i += 1
result.append([start, end])
# Phase 3: intervals that begin after the merged one ends
while i < n:
result.append(intervals[i])
i += 1
return result
JavaTested in our runner
import java.util.*;
class Solution {
public int[][] insert(int[][] intervals, int[] newInterval) {
List<int[]> result = new ArrayList<>();
int i = 0;
int n = intervals.length;
int start = newInterval[0];
int end = newInterval[1];
// Phase 1: intervals that finish before the new one starts
while (i < n && intervals[i][1] < start) {
result.add(intervals[i]);
i++;
}
// Phase 2: overlapping intervals are absorbed
while (i < n && intervals[i][0] <= end) {
start = Math.min(start, intervals[i][0]);
end = Math.max(end, intervals[i][1]);
i++;
}
result.add(new int[]{start, end});
// Phase 3: the rest
while (i < n) {
result.add(intervals[i]);
i++;
}
return result.toArray(new int[0][]);
}
}
C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
vector<vector<int>> result;
int i = 0;
int n = intervals.size();
int start = newInterval[0];
int end = newInterval[1];
// Phase 1: intervals that finish before the new one starts
while (i < n && intervals[i][1] < start) {
result.push_back(intervals[i]);
i++;
}
// Phase 2: overlapping intervals are absorbed
while (i < n && intervals[i][0] <= end) {
start = min(start, intervals[i][0]);
end = max(end, intervals[i][1]);
i++;
}
result.push_back({start, end});
// Phase 3: the rest
while (i < n) {
result.push_back(intervals[i]);
i++;
}
return result;
}
};
JavaScriptTested in our runner
/**
* @param {number[][]} intervals
* @param {number[]} newInterval
* @return {number[][]}
*/
var insert = function(intervals, newInterval) {
const result = [];
const n = intervals.length;
let i = 0;
let start = newInterval[0];
let end = newInterval[1];
// Phase 1: intervals that finish before the new one starts
while (i < n && intervals[i][1] < start) {
result.push(intervals[i]);
i++;
}
// Phase 2: overlapping intervals are absorbed
while (i < n && intervals[i][0] <= end) {
start = Math.min(start, intervals[i][0]);
end = Math.max(end, intervals[i][1]);
i++;
}
result.push([start, end]);
// Phase 3: the rest
while (i < n) {
result.push(intervals[i]);
i++;
}
return result;
};
GoTested in our runner
func insert(intervals [][]int, newInterval []int) [][]int {
result := [][]int{}
i, n := 0, len(intervals)
start, end := newInterval[0], newInterval[1]
// Phase 1: intervals that finish before the new one starts
for i < n && intervals[i][1] < start {
result = append(result, intervals[i])
i++
}
// Phase 2: overlapping intervals are absorbed
for i < n && intervals[i][0] <= end {
if intervals[i][0] < start {
start = intervals[i][0]
}
if intervals[i][1] > end {
end = intervals[i][1]
}
i++
}
result = append(result, []int{start, end})
// Phase 3: the rest
for i < n {
result = append(result, intervals[i])
i++
}
return result
}
C#Tested in our runner
public class Solution {
public int[][] insert(int[][] intervals, int[] newInterval) {
List<int[]> result = new List<int[]>();
int i = 0;
int n = intervals.Length;
int start = newInterval[0];
int end = newInterval[1];
// Phase 1: intervals that finish before the new one starts
while (i < n && intervals[i][1] < start) {
result.Add(intervals[i]);
i++;
}
// Phase 2: overlapping intervals are absorbed
while (i < n && intervals[i][0] <= end) {
start = Math.Min(start, intervals[i][0]);
end = Math.Max(end, intervals[i][1]);
i++;
}
result.Add(new int[] { start, end });
// Phase 3: the rest
while (i < n) {
result.Add(intervals[i]);
i++;
}
return result.ToArray();
}
}
Common mistakes
- Using
intervals[i][1] <= startin phase 1. An interval that ends exactly where the new one starts touches it and must merge. Use a strict<in phase 1 and<=in phase 2. - Using
intervals[i][0] < endin phase 2. That skips an interval starting exactly atend, so[8,10]would not merge with[4,8]. Write<=. - Appending
[start, end]inside the phase 2 loop. You would emit a partial interval for every overlap. Append once, after the loop finishes. - Forgetting the
i < nguard in awhileloop. When the new interval is larger than every existing one,intervals[i]reads past the end. Puti < nfirst in every condition. - Only taking
end = max(end, intervals[i][1])and leavingstartalone. The first overlapping interval can start earlier than the new one, as[1,3]does for[2,5]. Update both bounds withminandmax. - Sorting the whole list again after the pass, or inserting in the middle of an array. Both add cost the sorted input already saved you. Build a fresh result list in order.
Edge cases
intervals = [],newInterval = [5,7]: no loop runs, and the output is[[5,7]].- The new interval lies entirely left of all others, for example
[[3,4]]with[1,2]: phase 1 copies nothing, and the output is[[1,2],[3,4]]. - The new interval lies entirely right of all others, for example
[[1,2]]with[5,6]: phase 1 copies[1,2], and the output is[[1,2],[5,6]]. - The new interval touches an end point, for example
[[1,2],[4,5]]with[2,4]: all three merge into[[1,5]]. - The new interval swallows everything, for example
[[2,3],[5,6]]with[0,10]: the output is[[0,10]]. - The new interval sits inside one existing interval, for example
[[1,10]]with[3,4]: start stays 1, end stays 10, and the output is[[1,10]]. - The new interval is a single point, for example
[[1,5]]with[5,5]: it overlaps at 5, and the output is[[1,5]].
Follow-ups interviewers ask
- The list is sorted, so can you find the merge range faster than a linear scan?
- Yes, partly. Binary search for the first interval whose end is at least
newInterval.start, and for the last interval whose start is at mostnewInterval.end. Those two indices bound the overlap block in O(log n). You still have to copy the left and right groups into the output, so building the answer is O(n). If you could edit the array in place, such as in a linked list, the search would dominate. - How would you insert into a structure that you update many times?
- A sorted list rebuilt per insert costs O(n) each time. Use a balanced tree or an ordered map keyed by start. Find the neighbors in O(log n), remove the overlapping ones, and insert the merged interval. Each removed interval was inserted once, so the amortized cost stays O(log n) per insert.
- What changes if the input intervals are not sorted?
- The three-phase scan no longer works because overlapping intervals can be anywhere. Fall back to the first approach: append the new interval, sort by start, and merge in one sweep for O(n log n). Alternatively, one linear pass can still work. Keep intervals that do not touch the new one in the output, merge the ones that do, then sort the output once.
Insert Interval FAQ
What is the time complexity of Insert Interval?
The optimal scan is O(n), where n is the number of existing intervals. The shared index moves forward through three loops and never goes back. The sort-and-merge baseline is O(n log n) because of the sort.
Why use a greedy three-phase scan for Insert Interval?
The input is sorted and disjoint, so intervals fall into left, overlapping and right groups in that order. You can decide each interval's fate by comparing it with the current new interval, with no need to look back. That removes the sort and gives a single O(n) pass.
Can Insert Interval be solved in O(1) extra space?
Only if you count the output as free. Beyond the returned list, the scan keeps only i, start and end. The answer itself can hold n + 1 intervals, so building a new list costs O(n) space. An in-place version would need to shift array elements, which costs O(n) time per insert.
Do adjacent intervals like [1,2] and [2,3] merge in Insert Interval?
Yes. They share the point 2, so they overlap and become [1,3]. That is why phase 1 uses end < start strictly and phase 2 uses start <= end. Intervals like [1,2] and [3,4] have a gap and stay separate.
Can I use binary search for Insert Interval in Python or Java?
You can. Use bisect in Python or Arrays search logic in Java to find the first overlapping index and the last one. Then slice the list and build the result.
It lowers the search cost to O(log n), but the total stays O(n) because copying the output takes linear time. The linear scan is shorter and has fewer off-by-one risks.
How is Insert Interval different from Merge Intervals (LeetCode 56)?
Merge Intervals gives you an unsorted list, so you must sort first for O(n log n). Insert Interval gives you a sorted, disjoint list plus one extra interval, so a linear pass is enough. The merge rule inside the overlap phase is the same.
Asked at
See which companies ask this — Pro
Related problems
- Merge Intervals · same technique: Interval Merging/Scheduling
- Non-overlapping Intervals · same technique: Interval Merging/Scheduling
- Divide Intervals Into Minimum Number of Groups · same technique: Interval Merging/Scheduling
- Meeting Rooms · same technique: Interval Merging/Scheduling
- Candy · next harder, same pattern
- Jump Game · same pattern: Greedy Patterns
- Gas Station · same pattern: Greedy Patterns
- Task Scheduler · same pattern: Greedy Patterns
- Jump Game II · same pattern: Greedy Patterns
- Partition Labels · same pattern: Greedy Patterns