Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Insert and Merge Interval
Next article icon

Insert and Merge Interval

Last Updated : 26 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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].

Table of Content

  • [Naive Approach] Insertion and Merging - O(n*log n) Time and O(1) Space
  • [Expected Approach] Contiguous Interval Merging - O(n) Time and O(n) Space

[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]); } 

Output
1 3 4 7 8 10 

[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]); }; 

Output
1 3 4 7 8 10 

Next Article
Insert and Merge Interval

N

nik1996
Improve
Article Tags :
  • Sorting
  • DSA
  • Arrays
  • cpp-vector
  • Interval
Practice Tags :
  • Arrays
  • Sorting

Similar Reads

    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
    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), no
    15+ 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
    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
    Merge Overlapping Intervals
    Given an array of time intervals where arr[i] = [starti, endi], the task is to merge all the overlapping intervals into one and output the result which should have only mutually exclusive intervals. Examples:Input: arr[] = [[1, 3], [2, 4], [6, 8], [9, 10]]Output: [[1, 4], [6, 8], [9, 10]]Explanation
    13 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences