Insert and Merge Interval (original) (raw)

Last Updated : 7 Aug, 2025

Given a set of **non-overlapping intervals[][] where **intervals[i] = **[start i , end i ] represent the start and the end of the ith event and intervals is sorted in ascending order by **start i and a new **interval, 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].

Try It Yourselfredirect icon

Table of Content

[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 #include #include using namespace std;

// Function to merge overlapping intervals vector<vector> mergeOverlap(vector<vector>& 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> insertInterval(vector<vector>& intervals, vector &newInterval) { intervals.push_back(newInterval); return mergeOverlap(intervals); }

int main() { vector<vector> intervals = {{1, 3}, {4, 5}, {6, 7}, {8, 10}}; vector 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.Comparator;

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 #include #include using namespace std;

// Function to insert and merge intervals vector<vector> insertInterval(vector<vector>& intervals, vector &newInterval) { vector<vector> 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> intervals = {{1, 3}, {4, 5}, {6, 7}, {8, 10}}; vector 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]); };

`