Insert and Merge Interval
Last Updated :
26 Mar, 2025
Given a set of non-overlapping intervals and a new interval, the task is to insert the interval at the correct position such that after insertion, the intervals remain sorted. If the insertion results in overlapping intervals, then merge the overlapping intervals. Assume that the set of non-overlapping intervals is sorted based on start time.
Examples:
Input: intervals[][] = [[1, 3], [4, 5], [6, 7], [8, 10]], newInterval[] = [5, 6]
Output: [[1, 3], [4, 7], [8, 10]]
Explanation: The intervals [4, 5] and [6, 7] are overlapping with [5, 6]. So, they are merged into one interval [4, 7].
Input: intervals[][] = [[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]], newInterval[] = [4, 9]
Output: [[1, 2], [3, 10], [12, 16]]
Explanation: The intervals [ [3, 5], [6, 7], [8, 10] ] are overlapping with [4, 9]. So, they are merged into one interval [3, 10].
[Naive Approach] Insertion and Merging – O(n*log n) Time and O(1) Space
The approach is to append the new interval to the given array of intervals and then handle the overlapping of intervals. So, we will use the same approach as Merge Overlapping Intervals to merge the overlapping intervals after insertion.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to merge overlapping intervals
vector<vector<int>> mergeOverlap(vector<vector<int>>& intervals) {
// Sort intervals based on start values
sort(intervals.begin(), intervals.end());
vector<vector<int>> res;
// Insert the first interval into the result
res.push_back(intervals[0]);
for (int i = 1; i < intervals.size(); i++) {
// Find the last interval in the result
vector<int>& last = res.back();
vector<int>& curr = intervals[i];
// If current interval overlaps with the last interval
// in the result, merge them
if (curr[0] <= last[1])
last[1] = max(last[1], curr[1]);
else
res.push_back(curr);
}
return res;
}
vector<vector<int>> insertInterval(vector<vector<int>>& intervals,
vector<int> &newInterval) {
intervals.push_back(newInterval);
return mergeOverlap(intervals);
}
int main() {
vector<vector<int>> intervals = {{1, 3}, {4, 5}, {6, 7}, {8, 10}};
vector<int> newInterval = {5, 6};
vector<vector<int>> res = insertInterval(intervals, newInterval);
for (vector<int> interval: res) {
cout << interval[0] << " " << interval[1] << "\n";
}
return 0;
}
Java
import java.util.*;
class GfG {
// Function to merge overlapping intervals
static ArrayList<int[]> mergeOverlap(int[][] intervals) {
// Sort intervals based on start values
Arrays.sort(intervals, Comparator.comparingInt(a -> a[0]));
ArrayList<int[]> res = new ArrayList<>();
// Insert the first interval into the result
res.add(intervals[0]);
for (int i = 1; i < intervals.length; i++) {
// Find the last interval in the result
int[] last = res.get(res.size() - 1);
int[] curr = intervals[i];
// If current interval overlaps with the last interval
// in the result, merge them
if (curr[0] <= last[1]) {
last[1] = Math.max(last[1], curr[1]);
}
else {
res.add(curr);
}
}
return res;
}
static ArrayList<int[]> insertInterval(int[][] intervals,
int[] newInterval) {
// Create a new ArrayList to hold the intervals
ArrayList<int[]> intervalList =
new ArrayList<>(Arrays.asList(intervals));
intervalList.add(newInterval);
return mergeOverlap(intervalList.toArray(new int[0][]));
}
public static void main(String[] args) {
int[][] intervals = {{1, 3}, {4, 5}, {6, 7}, {8, 10}};
int[] newInterval = {5, 6};
ArrayList<int[]> res = insertInterval(intervals, newInterval);
for (int[] interval : res) {
System.out.println(interval[0] + " " + interval[1]);
}
}
}
Python
def mergeOverlap(intervals):
# Sort intervals based on start values
intervals.sort()
res = [intervals[0]]
for i in range(1, len(intervals)):
last = res[-1]
curr = intervals[i]
# If current interval overlaps with the last interval
# in the result, merge them
if curr[0] <= last[1]:
last[1] = max(last[1], curr[1])
else:
res.append(curr)
return res
def insertInterval(intervals, newInterval):
intervals.append(newInterval)
return mergeOverlap(intervals)
if __name__ == "__main__":
intervals = [[1, 3], [4, 5], [6, 7], [8, 10]]
newInterval = [5, 6]
res = insertInterval(intervals, newInterval)
for interval in res:
print(interval[0], interval[1])
C#
using System;
using System.Collections.Generic;
using System.Linq;
class GfG {
// Function to merge overlapping intervals
static List<int[]> mergeOverlap(int[][] intervals) {
// Sort intervals based on start values
Array.Sort(intervals, (a, b) => a[0].CompareTo(b[0]));
List<int[]> res = new List<int[]>();
// Insert the first interval into the result
res.Add(intervals[0]);
for (int i = 1; i < intervals.Length; i++) {
// Find the last interval in the result
int[] last = res[res.Count - 1];
int[] curr = intervals[i];
// If current interval overlaps with the last interval
// in the result, merge them
if (curr[0] <= last[1])
last[1] = Math.Max(last[1], curr[1]);
else
res.Add(curr);
}
return res;
}
static List<int[]> insertInterval(int[][] intervals, int[] newInterval) {
// Convert intervals to a list and add the new interval
List<int[]> intervalList = intervals.ToList();
intervalList.Add(newInterval);
return mergeOverlap(intervalList.ToArray());
}
static void Main(string[] args) {
int[][] intervals = new int[][] {
new int[] {1, 3},
new int[] {4, 5},
new int[] {6, 7},
new int[] {8, 10}
};
int[] newInterval = new int[] {5, 6};
List<int[]> res = insertInterval(intervals, newInterval);
foreach (int[] interval in res) {
Console.WriteLine(interval[0] + " " + interval[1]);
}
}
}
JavaScript
function mergeOverlap(intervals) {
// Sort intervals based on start values
intervals.sort((a, b) => a[0] - b[0]);
const res = [];
// Insert the first interval into the result
res.push(intervals[0]);
for (let i = 1; i < intervals.length; i++) {
// Find the last interval in the result
const last = res[res.length - 1];
const curr = intervals[i];
// If current interval overlaps with the last interval
// in the result, merge them
if (curr[0] <= last[1])
last[1] = Math.max(last[1], curr[1]);
else
res.push(curr);
}
return res;
}
function insertInterval(intervals, newInterval) {
intervals.push(newInterval);
return mergeOverlap(intervals);
}
// Driver Code
const intervals = [[1, 3], [4, 5], [6, 7], [8, 10]];
const newInterval = [5, 6];
const res = insertInterval(intervals, newInterval);
for (const interval of res) {
console.log(interval[0] + " " + interval[1]);
}
[Expected Approach] Contiguous Interval Merging – O(n) Time and O(n) Space
When we add a new interval, it may overlap with some contiguous intervals in the array. The overlapping intervals can be found in a contiguous subarray because the intervals array is already sorted. To remove overlapping we find these overlapping interval’s subarray and merge them with new interval, to form a single merged interval.
Now to maintain the order sorted, we first add the lower intervals, then this merged interval, and finally the remaining intervals in the result.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to insert and merge intervals
vector<vector<int>> insertInterval(vector<vector<int>>& intervals,
vector<int> &newInterval) {
vector<vector<int>> res;
int i = 0;
int n = intervals.size();
// Add all intervals that come before the new interval
while (i < n && intervals[i][1] < newInterval[0]) {
res.push_back(intervals[i]);
i++;
}
// Merge all overlapping intervals with the new interval
while (i < n && intervals[i][0] <= newInterval[1]) {
newInterval[0] = min(newInterval[0], intervals[i][0]);
newInterval[1] = max(newInterval[1], intervals[i][1]);
i++;
}
res.push_back(newInterval);
// Add all the remaining intervals
while (i < n) {
res.push_back(intervals[i]);
i++;
}
return res;
}
int main() {
vector<vector<int>> intervals = {{1, 3}, {4, 5}, {6, 7}, {8, 10}};
vector<int> newInterval = {5, 6};
vector<vector<int>> res = insertInterval(intervals, newInterval);
for (vector<int> interval: res) {
cout << interval[0] << " " << interval[1] << "\n";
}
return 0;
}
Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class GfG {
// Function to insert and merge intervals
static ArrayList<int[]> insertInterval(int[][] intervals, int[] newInterval) {
ArrayList<int[]> res = new ArrayList<>();
int i = 0;
int n = intervals.length;
// Add all intervals that come before the new interval
while (i < n && intervals[i][1] < newInterval[0]) {
res.add(intervals[i]);
i++;
}
// Merge all overlapping intervals with the new interval
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++;
}
res.add(newInterval);
// Add all the remaining intervals
while (i < n) {
res.add(intervals[i]);
i++;
}
// Return the result as a List<int[]>
return res;
}
public static void main(String[] args) {
int[][] intervals = {{1, 3}, {4, 5}, {6, 7}, {8, 10}};
int[] newInterval = {5, 6};
ArrayList<int[]> res = insertInterval(intervals, newInterval);
for (int[] interval : res) {
System.out.println(interval[0] + " " + interval[1]);
}
}
}
Python
def insertInterval(intervals, newInterval):
res = []
i = 0
n = len(intervals)
# Add all intervals that come before the new interval
while i < n and intervals[i][1] < newInterval[0]:
res.append(intervals[i])
i += 1
# Merge all overlapping intervals with the new interval
while i < n and intervals[i][0] <= newInterval[1]:
newInterval[0] = min(newInterval[0], intervals[i][0])
newInterval[1] = max(newInterval[1], intervals[i][1])
i += 1
res.append(newInterval)
# Add all the remaining intervals
while i < n:
res.append(intervals[i])
i += 1
return res
if __name__ == "__main__":
intervals = [[1, 3], [4, 5], [6, 7], [8, 10]]
newInterval = [5, 6]
res = insertInterval(intervals, newInterval)
for interval in res:
print(interval[0], interval[1])
C#
using System;
using System.Collections.Generic;
class GfG {
// Function to insert and merge intervals
static List<int[]> insertInterval(int[][] intervals, int[] newInterval) {
List<int[]> res = new List<int[]>();
int i = 0;
int n = intervals.Length;
// Add all intervals that come before the new interval
while (i < n && intervals[i][1] < newInterval[0]) {
res.Add(intervals[i]);
i++;
}
// Merge all overlapping intervals with the new interval
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++;
}
res.Add(newInterval);
// Add all the remaining intervals
while (i < n) {
res.Add(intervals[i]);
i++;
}
// Return result as List<int[]>
return res;
}
static void Main(string[] args) {
int[][] intervals = new int[][] {
new int[] {1, 3},
new int[] {4, 5},
new int[] {6, 7},
new int[] {8, 10}
};
int[] newInterval = new int[] {5, 6};
List<int[]> res = insertInterval(intervals, newInterval);
foreach (int[] interval in res) {
Console.WriteLine(interval[0] + " " + interval[1]);
}
}
}
JavaScript
function insertInterval(intervals, newInterval) {
let res = [];
let i = 0;
const n = intervals.length;
// Add all intervals that come before the new interval
while (i < n && intervals[i][1] < newInterval[0]) {
res.push(intervals[i]);
i++;
}
// Merge all overlapping intervals with the new interval
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++;
}
res.push(newInterval);
// Add all the remaining intervals
while (i < n) {
res.push(intervals[i]);
i++;
}
return res;
}
// Driver Code
const intervals = [[1, 3], [4, 5], [6, 7], [8, 10]];
const newInterval = [5, 6];
const res = insertInterval(intervals, newInterval);
for (const interval of res) {
console.log(interval[0] + " " + interval[1]);
};
Similar Reads
Insertion in a B+ tree
Prerequisite: Introduction of B+ treesIn this article, we will discuss that how to insert a node in B+ Tree. During insertion following properties of B+ Tree must be followed:Â Each node except root can have a maximum of M children and at least ceil(M/2) children.Each node can contain a maximum of M
15+ min read
Find Intersection of all Intervals
Given N intervals of the form of [l, r], the task is to find the intersection of all the intervals. An intersection is an interval that lies within all of the given intervals. If no such intersection exists, then print -1. Examples: Input: arr[] = {{1, 6}, {2, 8}, {3, 10}, {5, 8}} Output: [5, 6] Exp
5 min read
Merge Sort Interview Questions and Answers
Merge sort is defined as a sorting algorithm that works by dividing an array into smaller subarrays, sorting each subarray, and then merging the sorted subarrays back together to form the final sorted array. Let us discuss some of the interview questions asked about Merge Sort: 1. Is Merge sort In P
4 min read
Vector insert() in C++ STL
In C++, the vector insert() is a built-in function used to insert new elements at the given position in a vector. In this article, we will learn about the vector insert() function in C++. Letâs take a look at an example that shows the how to use this function: [GFGTABS] C++ #include <bits/stdc++.
4 min read
Insert Operation in B-Tree
In this post, we'll discuss the insert() operation in a B-Tree. A new key is always inserted into a leaf node. To insert a key k, we start from the root and traverse down the tree until we reach the appropriate leaf node. Once there, the key is added to the leaf. Unlike Binary Search Trees (BSTs), n
15+ min read
Maximal Disjoint Intervals
Given a 2D array arr[][] of order nx2, representing n intervals with start and end points, the task is to find the maximal set of mutually disjoint intervals Note: Two intervals [i, j] & [k, l] are said to be disjoint if they do not have any point in common. Examples: Input: arr[][] = [[1, 4], [
11 min read
Interval Tree
You are given a set of intervals, where each interval contains two variables, low and high, that defines the start and end time of the interval. The task is perform the following operations efficiently: Add an intervalRemove an intervalGiven an interval x, find if x overlaps with any of the existing
15+ min read
Non-overlapping intervals in an array
Given a 2d array arr[][] of time intervals, where each interval is of the form [start, end]. The task is to determine all intervals from the given array that do not overlap with any other interval in the set. If no such interval exists, return an empty list. Examples: Input: arr[] = [[1, 3], [2, 4],
5 min read
Coding Problems on Interval and Range Manipulation
Interval and Range Manipulation problems are common in algorithmic challenges, often requiring efficient handling of ranges or intervals to solve a specific problem. These problems deal with tasks like merging intervals, finding overlaps, or calculating sums and differences of intervals. The main ch
2 min read
Remove Interval from Disjoint Intervals
Given a sorted list of disjoint intervals representing a set of real numbers and an interval toBeRemoved to remove. The task is to remove toBeRemoved interval from the set and return the remaining intervals as a sorted list. Example: Input: intervals = {{0,2},{3,4},{5,7}}, toBeRemoved = {1,6}Output:
7 min read