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 Problems on Heap
  • Practice Heap
  • MCQs on Heap
  • Heap Tutorial
  • Binary Heap
  • Building Heap
  • Binomial Heap
  • Fibonacci Heap
  • Heap Sort
  • Heap vs Tree
  • Leftist Heap
  • K-ary Heap
  • Advantages & Disadvantages
Open In App
Next Article:
Non-overlapping intervals in an array
Next article icon

Non-overlapping intervals in an array

Last Updated : 26 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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], [3, 5], [7, 9]] 
Output: [[5, 7]] 
Explanation: The only interval which doesn’t overlaps with the other intervals is [5, 7].

Input: arr[][] = [[1, 3], [2, 6], [8, 10], [15, 18]] 
Output: [[6, 8], [10, 15]]
Explanation: There are two intervals which don’t overlap with other intervals are [6, 8], [10, 15].

Input: arr[][] = [[1, 3], [9, 12], [2, 4], [6, 8]] 
Output: [[4, 6], [8, 9]] 
Explanation: There are two intervals which don’t overlap with other intervals are [4, 6], [8, 9].

Approach:

The idea is to sort the given time intervals according to starting time and if the consecutive intervals don't overlap then the difference between them is the free interval. 

Steps to implement the above idea:

  • Sort the given set of intervals according to starting time.
  • Traverse all the set of intervals and check whether the consecutive intervals overlaps or not.
  • If the intervals(say interval a & interval b) do no't overlap then the set of pairs form by [a.end, b.start] is the non-overlapping interval.
  • If the intervals overlaps, then check for next consecutive intervals. 
C++
#include <bits/stdc++.h> using namespace std;  vector<vector<int>> findGaps(vector<vector<int>> &arr) {     if (arr.empty()) return {};          // Sort intervals by start time     sort(arr.begin(), arr.end());          vector<vector<int>> res;     for (int i = 1; i < arr.size(); i++) {                  // End of previous and start of current are         // are checked and if non-overlapping, then         // added to the result         if (arr[i - 1][1] < arr[i][0]) {             res.push_back({arr[i - 1][1], arr[i][0]});         }     }     return res; }  int main() {     vector<vector<int>> arr = {{1, 3}, {2, 6}, {8, 10}, {15, 18}};          for (auto &gap : findGaps(arr)) {         cout << "[" << gap[0] << ", " << gap[1] << "] ";     }     return 0; } 
Java
import java.util.ArrayList; import java.util.Arrays; import java.util.List;  public class Main {     public static List<int[]> findGaps(int[][] arr) {         if (arr.length == 0) {             return new ArrayList<>();         }                  // Sort intervals by start time         Arrays.sort(arr, (a, b) -> Integer.compare(a[0], b[0]));                  List<int[]> res = new ArrayList<>();         for (int i = 1; i < arr.length; i++) {                          // End of previous and start of current are             // are checked and if non-overlapping, then             // added to the result             if (arr[i - 1][1] < arr[i][0]) {                 res.add(new int[]{arr[i - 1][1], arr[i][0]});             }         }         return res;     }          public static void main(String[] args) {         int[][] arr = {{1, 3}, {2, 6}, {8, 10}, {15, 18}};                  for (int[] gap : findGaps(arr)) {             System.out.print("[" + gap[0] + ", " + gap[1] + "] ");         }     } } 
Python
def find_gaps(arr):     if not arr:         return []          # Sort intervals by start time     arr.sort()          res = []     for i in range(1, len(arr)):                  # End of previous and start of current are         # are checked and if non-overlapping, then         # added to the result         if arr[i - 1][1] < arr[i][0]:             res.append([arr[i - 1][1], arr[i][0]])     return res  if __name__ == '__main__':     arr = [[1, 3], [2, 6], [8, 10], [15, 18]]          for gap in find_gaps(arr):         print(f'[{gap[0]}, {gap[1]}]', end=' ') 
C#
using System; using System.Collections.Generic; using System.Linq;  public class MainClass {     public static List<int[]> FindGaps(int[][] arr) {         if (arr.Length == 0) {             return new List<int[]>();         }                  // Sort intervals by start time         Array.Sort(arr, (a, b) => a[0].CompareTo(b[0]));                  List<int[]> res = new List<int[]>();         for (int i = 1; i < arr.Length; i++) {                          // End of previous and start of current are             // checked and if non-overlapping, then             // added to the result             if (arr[i - 1][1] < arr[i][0]) {                 res.Add(new int[] { arr[i - 1][1], arr[i][0] });             }         }         return res;     }          public static void Main(string[] args) {         int[][] arr = new int[][] { new int[] { 1, 3 }, new int[] { 2, 6 }, new int[] { 8, 10 }, new int[] { 15, 18 } };                  foreach (int[] gap in FindGaps(arr)) {             Console.Write("[" + gap[0] + ", " + gap[1] + "] ");         }     } } 
JavaScript
function findGaps(arr) {     if (arr.length === 0) {         return [];     }          // Sort intervals by start time     arr.sort((a, b) => a[0] - b[0]);          const res = [];     for (let i = 1; i < arr.length; i++) {                  // End of previous and start of current are         // checked and if non-overlapping, then         // added to the result         if (arr[i - 1][1] < arr[i][0]) {             res.push([arr[i - 1][1], arr[i][0]]);         }     }     return res; }  const arr = [[1, 3], [2, 6], [8, 10], [15, 18]];  for (const gap of findGaps(arr)) {     console.log(`[${gap[0]}, ${gap[1]}]`); } 

Output
[[6, 8], [10, 15]] 

Time Complexity: O(n*log(n)), where n is the number of set of intervals.
Auxiliary Space: O(n)
 


Next Article
Non-overlapping intervals in an array

C

coder001
Improve
Article Tags :
  • Sorting
  • Heap
  • Competitive Programming
  • DSA
  • Interval
Practice Tags :
  • Heap
  • Sorting

Similar Reads

    Non-Overlapping Intervals
    Given a list of intervals with starting and ending values, the task is to find the minimum number of intervals that are required to be removed to make remaining intervals non-overlapping. Examples:Input: intervals[][] = [[1, 2], [2, 3], [3, 4], [1, 3]]Output: 1 Explanation: Removal of [1, 3] makes t
    9 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
    Find a pair of overlapping intervals from a given Set
    Given a 2D array arr[][] with each row of the form {l, r}, the task is to find a pair (i, j) such that the ith interval lies within the jth interval. If multiple solutions exist, then print anyone of them. Otherwise, print -1. Examples: Input: N = 5, arr[][] = { { 1, 5 }, { 2, 10 }, { 3, 10}, {2, 2}
    11 min read
    Find least non-overlapping number from a given set of intervals
    Given an array interval of pairs of integers representing the starting and ending points of the interval of size N. The task is to find the smallest non-negative integer which is a non-overlapping number from the given set of intervals. Input constraints: 1 ≤ N ≤ 10^{5}0 ≤ interval[i] ≤ 10^{9} Examp
    15+ min read
    Print a pair of indices of an overlapping interval from given array
    Given a 2D array arr[][] of size N, with each row representing intervals of the form {X, Y} ( 1-based indexing ), the task to find a pair of indices of overlapping intervals. If no such pair exists, then print -1 -1. Examples: Input: N = 5, arr[][] = {{1, 5}, {2, 10}, {3, 10}, {2, 2}, {2, 15}}Output
    12 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