The Wayback Machine - https://web.archive.org/web/20241007013707/https://www.geeksforgeeks.org/find-non-overlapping-intervals-among-a-given-set-of-intervals/
Open In App

Find Non-overlapping intervals among a given set of intervals

Last Updated : 03 Jan, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given N set of time intervals, the task is to find the intervals which don’t overlap with the given set of intervals.
Examples: 
 

Input: interval 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: interval 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. 
Below are the steps: 
 

  1. Sort the given set of intervals according to starting time.
  2. Traverse all the set of intervals and check whether the consecutive intervals overlaps or not.
  3. If the intervals(say interval a & interval b) doesn’t overlap then the set of pairs form by [a.end, b.start] is the non-overlapping interval.
  4. If the intervals overlaps, then check for next consecutive intervals.

Below is the implementation of the above approach: 
 

C++




// C++ program for the above approach
 
#include "bits/stdc++.h"
using namespace std;
 
// interval with start time & end time
struct interval {
    int start, end;
};
 
// Comparator function to sort the given
// interval according to time
bool compareinterval(interval i1, interval i2)
{
    return (i1.start < i2.start);
}
 
// Function that find the free interval
void findFreeinterval(interval arr[], int N)
{
 
    // If there are no set of interval
    if (N <= 0) {
        return;
    }
 
    // To store the set of free interval
    vector<pair<int, int> > P;
 
    // Sort the given interval according
    // starting time
    sort(arr, arr + N, compareinterval);
 
    // Iterate over all the interval
    for (int i = 1; i < N; i++) {
 
        // Previous interval end
        int prevEnd = arr[i - 1].end;
 
        // Current interval start
        int currStart = arr[i].start;
 
        // If ending index of previous
        // is less than starting index
        // of current, then it is free
        // interval
        if (prevEnd < currStart) {
            P.push_back({ prevEnd,
                          currStart });
        }
    }
 
    // Print the free interval
    for (auto& it : P) {
        cout << "[" << it.first << ", "
             << it.second << "]" << endl;
    }
}
 
// Driver Code
int main()
{
 
    // Given set of interval
    interval arr[] = { { 1, 3 },
                       { 2, 4 },
                       { 3, 5 },
                       { 7, 9 } };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    findFreeinterval(arr, N);
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
class GFG {
     
// Interval with start time & end time
static class Interval
{
    int start, end;
 
    Interval(int start, int end)
    {
        this.start = start;
        this.end = end;
    }
}
 
// Function that find the free interval
static void findFreeinterval(int[][] arr, int N)
{
    // If there are no set of interval
    if (N <= 0)
    {
        return;
    }
 
    // To store the set of free interval
    ArrayList<Interval> p = new ArrayList<>();
 
    // Sort the given interval according
    // starting time
    Arrays.sort(arr, new Comparator<int[]>()
    {
        public int compare(int[] a, int[] b)
        {
            return a[0] - b[0];
        }
    });
 
    // Iterate over all the interval
    for (int i = 1; i < N; i++)
    {
 
        // Previous interval end
        int prevEnd = arr[i - 1][1];
 
        // Current interval start
        int currStart = arr[i][0];
 
        // If ending index of previous
        // is less than starting index
        // of current, then it is free
        // interval
        if (prevEnd < currStart)
        {
            Interval interval = new Interval(prevEnd,
                                              currStart);
            p.add(interval);
        }
    }
 
    // Print the free interval
    for (int i = 0; i < p.size(); i++)
    {
        System.out.println("[" + p.get(i).start +
                          ", " + p.get(i).end + "]");
    }
}
 
// Driver code
public static void main(String[] args)
{
 
    // Given set of interval
    int[][] arr = { { 1, 3 },
                    { 2, 4 },
                    { 3, 5 },
                    { 7, 9 } };
 
    int N = arr.length;
 
    // Function Call
    findFreeinterval(arr, N);
}
}
 
// This code is contributed by offbeat


Python3




# Python3 program for the above approach
def findFreeinterval(arr, N):
     
    # If there are no set of interval
    if N < 1:
        return
     
    # To store the set of free interval
    P = []
     
    # Sort the given interval according
    # Starting time
    arr.sort(key = lambda a:a[0])
     
    # Iterate over all the interval
    for i in range(1, N):
         
        # Previous interval end
        prevEnd = arr[i - 1][1]
         
        # Current interval start
        currStart = arr[i][0]
         
        # If Previous Interval is less
        # than current Interval then we
        # store that answer
        if prevEnd < currStart:
            P.append([prevEnd, currStart])
     
    # Print the intervals
    for i in P:
        print(i)
     
# Driver code
if __name__ == "__main__":
     
    # Given List of intervals
    arr = [ [ 1, 3 ], [ 2, 4 ],
            [ 3, 5 ], [ 7, 9 ] ]
     
    N = len(arr)
     
    # Function call
    findFreeinterval(arr, N)
     
# This code is contributed by Tokir Manva


C#




using System;
using System.Linq;
using System.Collections.Generic;
 
class GFG {
  // Interval with start time & end time
  class Interval {
    public int start, end;
 
    public Interval(int start, int end)
    {
      this.start = start;
      this.end = end;
    }
  }
 
  // Function that find the free interval
  static void FindFreeInterval(int[][] arr, int N)
  {
    // If there are no set of interval
    if (N <= 0) {
      return;
    }
 
    // To store the set of free interval
    List<Interval> p = new List<Interval>();
 
    // Sort the given interval according
    // starting time
    Array.Sort(arr, new Comparison<int[]>(
      (a, b) => a[0] - b[0]));
 
    // Iterate over all the interval
    for (int i = 1; i < N; i++) {
      // Previous interval end
      int prevEnd = arr[i - 1][1];
 
      // Current interval start
      int currStart = arr[i][0];
 
      // If ending index of previous
      // is less than starting index
      // of current, then it is free
      // interval
      if (prevEnd < currStart) {
        Interval interval
          = new Interval(prevEnd, currStart);
        p.Add(interval);
      }
    }
 
    // Print the free interval
    for (int i = 0; i < p.Count; i++) {
      Console.WriteLine("[" + p[i].start + ", "
                        + p[i].end + "]");
    }
  }
 
  // Driver Code
  static void Main(string[] args)
  {
    // Given set of interval
    int[][] arr
      = { new int[] { 1, 3 }, new int[] { 2, 4 },
         new int[] { 3, 5 }, new int[] { 7, 9 } };
 
    int N = arr.Length;
 
    // Function Call
    FindFreeInterval(arr, N);
  }
}
 
// This code is contributed by phasing17


Javascript




<script>
 
// Javascript program for the above approach
 
// Function that find the free interval
function findFreeinterval(arr, N)
{
 
    // If there are no set of interval
    if (N <= 0) {
        return;
    }
 
    // To store the set of free interval
    var P = [];
 
    // Sort the given interval according
    // starting time
    arr.sort((a,b) => a[0]-b[0])
 
    // Iterate over all the interval
    for (var i = 1; i < N; i++) {
 
        // Previous interval end
        var prevEnd = arr[i - 1][1];
 
        // Current interval start
        var currStart = arr[i][0];
 
        // If ending index of previous
        // is less than starting index
        // of current, then it is free
        // interval
        if (prevEnd < currStart) {
            P.push([prevEnd,
                          currStart]);
        }
    }
 
    // Print the free interval
    P.forEach(it => {
 
        document.write( "[" + it[0] + ", "
             + it[1] + "]");
    });
}
 
// Driver Code
 
// Given set of interval
var arr = [ [ 1, 3 ],
                   [ 2, 4 ],
                   [ 3, 5 ],
                   [ 7, 9 ] ];
var N = arr.length;
 
// Function Call
findFreeinterval(arr, N);
 
// This code is contributed by noob2000.
</script>


Output: 

[5, 7]

 

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

Auxiliary Space: O(N)
 



Similar Reads

Maximum sum of at most two non-overlapping intervals in a list of Intervals | Interval Scheduling Problem
Given an array interval of length N, where each element represents three values, i.e. {startTime, endTime, value}. The task is to find the maximum sum of values of at most two non-overlapping intervals. Example: Input: interval[] = [[1, 3, 2], [4, 5, 2], [2, 4, 3]]Output: 4Explanation: Select interval 1 and 2 (as third interval is overlapping). The
7 min read
Check if any two intervals intersects among a given set of intervals
An interval is represented as a combination of start time and end time. Given a set of intervals, check if any two intervals intersect. Examples: Input: arr[] = {{1, 3}, {5, 7}, {2, 4}, {6, 8}} Output: true The intervals {1, 3} and {2, 4} overlap Input: arr[] = {{1, 3}, {7, 9}, {4, 6}, {10, 13}} Output: false No pair of intervals overlap. Expected
13 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: [Tex]1 â‰Ī N â‰Ī 10^{5}0 â‰Ī interval[i] â‰Ī 10^{9} [/Tex] Examples: Input: interval = {{0, 4}, {6, 8}
15+ min read
Find index of closest non-overlapping interval to right of each of given N intervals
Given an array arr[] of N intervals, the task is to calculate the index of the closest interval to the right of each of the given N intervals that do not overlap with the current interval. Examples: Input: arr[] = {{3, 4}, {2, 3}, {1, 2}}Output: -1 0 1Explanation: For the interval arr[0], there exists no interval to the right of it. For interval ar
7 min read
Check if given intervals can be made non-overlapping by adding/subtracting some X
Given an array arr[] containing N intervals, the task is to check that if the intervals can be added or subtracted by X after which there are no overlapping intervals. Here X be any real number. Examples: Input: arr[] = {[1, 3], [2, 4], [4, 5], [5, 6]} Output: YES Explanation: We can add X = 1000 in [Tex]1^{st} [/Tex]and [Tex]3^{rd} [/Tex]intervals
9 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}, {2, 15}}Output: 3 0Explanation: [2, 2] lies insi
11 min read
Count of available non-overlapping intervals to be inserted to make interval [0, R]
Given an integer R which signifies the range [0, R] and two arrays start[] and end[] of size N which signifies the starting and ending intervals in the range [0, R]. The task is to count the number of available non-overlapping intervals which need to be inserted in the arrays such that on merging the individual ranges in the arrays start[] and end[
13 min read
Make the intervals non-overlapping by assigning them to two different processors
Given a list of intervals interval[] where each interval contains two integers L and R, the task is to assign intervals to two different processors such that there are no overlapping intervals for each processor. To assign the interval[i] to the first processor, print "F" and to assign it to the second processor, print "S".Note: If there is no poss
8 min read
Split Array into K non-overlapping subset such that maximum among all subset sum is minimum
Given an array arr[] consisting of N integers and an integer K, the task is to split the given array into K non-overlapping subsets such that the maximum among the sum of all subsets is minimum. Examples: Input: arr[] = {1, 7, 9, 2, 12, 3, 3}, M = 3Output: 13Explanation:One possible way to split the array into 3 non-overlapping subsets is {arr[4],
7 min read
Maximum number of overlapping Intervals
Given different intervals, the task is to print the maximum number of overlap among these intervals at any time. Examples:  Input: v = {{1, 2}, {2, 4}, {3, 6}} Output: 2 The maximum overlapping is 2(between (1 2) and (2 4) or between (2 4) and (3 6))   Input: v = {{1, 8}, {2, 5}, {5, 6}, {3, 7}} Output: 4 The maximum overlapping is 4 (between (1, 8
7 min read
Merge Overlapping Intervals
Given a set of time intervals in any order, our task is to merge all overlapping intervals into one and output the result which should have only mutually exclusive intervals. Example: Input: arr = {{1,3},{2,4},{6,8},{9,10}}Output: {{1, 4}, {6, 8}, {9, 10}}Explanation: Given intervals: [1,3],[2,4],[6,8],[9,10], we have only two overlapping intervals
11 min read
Find two non-overlapping pairs having equal sum in an Array
Given an unsorted array of integers. The task is to find any two non-overlapping pairs whose sum is equal.Two pairs are said to be non-overlapping if all the elements of the pairs are at different indices. That is, pair (Ai, Aj) and pair (Am, An) are said to be non-overlapping if i ? j ? m ? n. Examples: Input: arr[] = {8, 4, 7, 8, 4} Output: Pair
8 min read
Count pairs of non-overlapping palindromic sub-strings of the given string
Given a string S. The task is to count the non-overlapping pairs of palindromic sub-strings S1 and S2 such that the strings should be S1[L1...R1] and S2[L2...R2] where 0 ? L1 ? R1 < L2 ? R2 < N. The task is to count the number of pairs of the non-overlapping palindromic sub-strings. Examples: Input: s = "aaa" Output: 5 All possible pairs are
13 min read
Count of non-overlapping sub-strings "101" and "010" in the given binary string
Given binary string str, the task is to find the count of non-overlapping sub-strings of either the form "010" or "101". Examples: Input: str = "10101010101" Output: 3 str[0..2] = "101" str[3..5] = "010" str[6..8] = "101"Input: str = "111111111111110" Output: 0 Approach: Initialize count = 0 and for every index i in the given string check whether t
5 min read
Count maximum non-overlapping subarrays with given sum
Given an array arr[] consisting of N integers and an integer target, the task is to find the maximum number of non-empty non-overlapping subarrays such that the sum of array elements in each subarray is equal to the target. Examples: Input: arr[] = {2, -1, 4, 3, 6, 4, 5, 1}, target = 6Output: 3Explanation: Subarrays {-1, 4, 3}, {6} and {5, 1} have
7 min read
Make given segments non-overlapping by assigning directions
Given an array arr[][] consisting of N segments of the form {L, R, V} where, [L, R] denotes a segment with velocity V in any direction, the task is to check if it is possible to assign directions as left or right to all the segments such that they do not intersect after a long period of time. Examples: Input: arr[][] = {{5, 7, 2}, {4, 6, 1}, {1, 5,
14 min read
Size of smallest square that contains N non-overlapping rectangles of given dimensions
Given two positive integers W and H and N rectangles of dimension W*H, the task is to find the smallest size of the square required such that all the N rectangles can be packed without overlapping. Examples: Input: N = 10, W = 2, H = 3Output: 9Explanation:The smallest size of the square is 9 units to pack the given 10 rectangles of size 2*3 as illu
7 min read
Kth non-overlapping Substring of length M after sorting given String lexicographically
Given string str of size N and two integers M and K (N is divisible by M), the task is to find the Kth non-overlapping substring of size M after sorting the given string lexicographically Examples: Input: str = "hwnriw", M = 3, K = 1Output: hinExplanation: Non overlapping substrings of size 3 after sorting are "hin" "rww". So 1st string is "hin" .
13 min read
Maximum sum two non-overlapping subarrays of given size
Given an array, we need to find two subarrays with a specific length K such that sum of these subarrays is maximum among all possible choices of subarrays. Examples: Input : arr[] = [2, 5, 1, 2, 7, 3, 0] K = 2 Output : 2 5 7 3 We can choose two arrays of maximum sum as [2, 5] and [7, 3], the sum of these two subarrays is maximum among all possible
12 min read
Maximum sum of non-leaf nodes among all levels of the given binary tree
Given a Binary Tree having positive and negative nodes, the task is to find the maximum sum of non-leaf nodes among all levels of the given binary tree. Examples: Input: 4 / \ 2 -5 / \ -1 3 Output: 4 Sum of all non-leaf nodes at 0th level is 4. Sum of all non-leaf nodes at 1st level is 2. Sum of all non-leaf nodes at 2nd level is 0. Hence maximum s
9 min read
Count of distinct GCDs among all the non-empty subsequences of given array
Given an integer array arr[] of size N, the task is to calculate the total number of distinct Greatest Common Divisors(GCDs) among all the non-empty subsequences of arr[]. Examples: Input: arr[]={3,4,8} N=3Output:4Explanation:The different non-empty subsequences possible are {3}, {4}, {8}, {3,4}, {4,8}, {3,8}, {3,4,8} and their corresponding GCDs a
8 min read
Max sum of M non-overlapping subarrays of size K
Given an array and two numbers M and K. We need to find the max sum of sums of M subarrays of size K (non-overlapping) in the array. (Order of array remains unchanged). K is the size of subarrays and M is the count of subarray. It may be assumed that size of array is more than m*k. If total array size is not multiple of k, then we can take partial
9 min read
Check if a string contains two non overlapping sub-strings "geek" and "keeg"
Given a string str, the task is to check whether the string contains two non-overlapping sub-strings s1 = "geek" and s2 = "keeg" such that s2 starts after s1 ends.Examples: Input: str = "geekeekeeg" Output: Yes "geek" and "keeg" both are present in the given string without overlapping.Input: str = "geekeeg" Output: No "geek" and "keeg" both are pre
3 min read
Count of three non-overlapping sub-strings which on concatenation forms a palindrome
Given a string str, the task is to count the number of ways a palindromic substring could be formed by the concatenation of three sub-strings x, y and z of the string str such that all of them are non-overlapping i.e. sub-string y occurs after substring x and sub-string z occurs after sub-string y.Examples: Input: str = "abca" Output: 2 The two val
7 min read
Maximise array sum after taking non-overlapping sub-arrays of length K
Given an integer array arr[] of length N and an integer K, the task is to select some non-overlapping sub-arrays such that each sub-array is exactly of length K, no two sub-arrays are adjacent and sum of all the elements of the selected sub-arrays is maximum.Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 2 Output: 12 Sub-arrays that maximizes sum wi
8 min read
Maximum sum of non-overlapping subarrays of length atmost K
Given an integer array 'arr' of length N and an integer 'k', select some non-overlapping subarrays such that each sub-array if of length at most 'k', no two sub-arrays are adjacent and sum of all the elements of the selected sub-arrays are maximum.Examples: Input : arr[] = {-1, 2, -3, 4, 5}, k = 2 Output : 11 Sub-arrays that maximizes sum will be {
10 min read
Maximum number of times str1 appears as a non-overlapping substring in str2
Given two strings str1 and str2, the task is to find the maximum number of times str1 occurs in str2 as a non-overlapping substring after rearranging the characters of str2Examples: Input: str1 = "geeks", str2 = "gskefrgoekees" Output: 2 str = "geeksforgeeks"Input: str1 = "aa", str2 = "aaaa" Output: 2 Approach: The idea is to store the frequency of
7 min read
Maximize count of non-overlapping subarrays with sum K
Given an array arr[] and an integer K, the task is to print the maximum number of non-overlapping subarrays with a sum equal to K. Examples: Input: arr[] = {-2, 6, 6, 3, 5, 4, 1, 2, 8}, K = 10Output: 3Explanation: All possible non-overlapping subarrays with sum K(= 10) are {-2, 6, 6}, {5, 4, 1}, {2, 8}. Therefore, the required count is 3. Input: ar
6 min read
Maximize count of non overlapping substrings which contains all occurrences of its characters
Given string str consisting of lowercase letters, the task is to find the maximum number of non-overlapping substrings such that each substring contains all occurrences of its characters from the entire string. If multiple solutions with the same number of substrings exist, then print the one with the minimum total length. Examples: Input: str = "a
12 min read
Check if a string consists of two K-length non-overlapping substrings as anagrams
Given a string str of length N and an integer K, the task is to check if a string has two non-overlapping substrings of length K as anagrams. Examples: Input: str = "ginfing", K = 3Output: YesExplanation:"gin" and "ing" are the two non overlapping substrings of length 3 which are anagrams.Therefore, the output is Yes. Input: str = "ginig", K = 3Out
9 min read
Practice Tags :