The Wayback Machine - https://web.archive.org/web/20240907142504/https://www.geeksforgeeks.org/maximum-number-of-overlapping-intervals/
Open In App

Maximum number of overlapping Intervals

Last Updated : 16 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Hard
40.71%
2.3K

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), (2, 5), (5, 6) and (3, 7))
 

Approach: 

  • The idea is to store coordinates in a new vector of pair mapped with characters ‘x’ and ‘y’, to identify coordinates.
  • Sort the vector.
  • Traverse the vector, if an x coordinate is encountered it means a new range is added, so update count and if y coordinate is encountered that means a range is subtracted.
  • Update the value of count for every new coordinate and take maximum.

Below is the implementation of the above approach:
 

C++
// C++ program that print maximum
// number of overlap
// among given ranges
#include <bits/stdc++.h>
using namespace std;

// Function that print maximum
// overlap among ranges
void overlap(vector<pair<int, int> > v)
{
    // variable to store the maximum
    // count
    int ans = 0;
    int count = 0;
    vector<pair<int, char> > data;

    // storing the x and y
    // coordinates in data vector
    for (int i = 0; i < v.size(); i++) {

        // pushing the x coordinate
        data.push_back({ v[i].first, 'x' });

        // pushing the y coordinate
        data.push_back({ v[i].second, 'y' });
    }

    // sorting of ranges
    sort(data.begin(), data.end());

    // Traverse the data vector to
    // count number of overlaps
    for (int i = 0; i < data.size(); i++) {

        // if x occur it means a new range
        // is added so we increase count
        if (data[i].second == 'x')
            count++;

        // if y occur it means a range
        // is ended so we decrease count
        if (data[i].second == 'y')
            count--;

        // updating the value of ans
        // after every traversal
        ans = max(ans, count);
    }

    // printing the maximum value
    cout << ans << endl;
}

// Driver code
int main()
{
    vector<pair<int, int> > v
        = { { 1, 2 }, { 2, 4 }, { 3, 6 } };
    overlap(v);
    return 0;
}
Java
// Java program that print maximum 
// number of overlap among given ranges 
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG{
    
static class pair
{
    int first;
    char second;
    
    pair(int first, char second)
    {
        this.first = first;
        this.second = second;
    }
}

// Function that print maximum 
// overlap among ranges 
static void overlap(int[][] v) 
{ 
    
    // Variable to store the maximum 
    // count 
    int ans = 0; 
    int count = 0; 
    ArrayList<pair> data = new ArrayList<>(); 
    
    // Storing the x and y 
    // coordinates in data vector 
    for(int i = 0; i < v.length; i++)
    { 
        
        // Pushing the x coordinate 
        data.add(new pair(v[i][0], 'x')); 
  
        // pushing the y coordinate 
        data.add(new pair(v[i][1], 'y')); 
    } 
    
    // Sorting of ranges 
    Collections.sort(data, (a, b) -> a.first - b.first); 
  
    // Traverse the data vector to 
    // count number of overlaps 
    for(int i = 0; i < data.size(); i++) 
    { 
        
        // If x occur it means a new range 
        // is added so we increase count 
        if (data.get(i).second == 'x') 
            count++; 
  
        // If y occur it means a range 
        // is ended so we decrease count 
        if (data.get(i).second == 'y') 
            count--; 
  
        // Updating the value of ans 
        // after every traversal 
        ans = Math.max(ans, count); 
    } 
  
    // Printing the maximum value 
    System.out.println(ans); 
}

// Driver code
public static void main(String[] args) 
{
    int[][] v = { { 1, 2 }, 
                  { 2, 4 }, 
                  { 3, 6 } }; 
    overlap(v); 
}
}

// This code is contributed by offbeat
Python
# Python3 program that print maximum
# number of overlap
# among given ranges

# Function that print maximum
# overlap among ranges
def overlap(v):

    # variable to store the maximum
    # count
    ans = 0
    count = 0
    data = []

    # storing the x and y
    # coordinates in data vector
    for i in range(len(v)):

        # pushing the x coordinate
        data.append([v[i][0], 'x'])

        # pushing the y coordinate
        data.append([v[i][1], 'y'])

    # sorting of ranges
    data = sorted(data)

    # Traverse the data vector to
    # count number of overlaps
    for i in range(len(data)):

        # if x occur it means a new range
        # is added so we increase count
        if (data[i][1] == 'x'):
            count += 1

        # if y occur it means a range
        # is ended so we decrease count
        if (data[i][1] == 'y'):
            count -= 1

        # updating the value of ans
        # after every traversal
        ans = max(ans, count)

    # printing the maximum value
    print(ans)

# Driver code
v = [ [ 1, 2 ], [ 2, 4 ], [ 3, 6 ] ]
overlap(v)

# This code is contributed by mohit kumar 29
C#
// Include namespace system
using System;
using System.Collections.Generic;

public class GFG
{
     class pair
    {
        public int first;
        public char second;
        public pair(int first, char second)
        {
            this.first = first;
            this.second = second;
        }
    }
  
    // Function that print maximum
    // overlap among ranges
    public static void overlap(int[,] v)
    {
      
        // Variable to store the maximum
        // count 
        var ans = 0;
        var count = 0;
        var data = new List<pair>();
      
        // Storing the x and y
        // coordinates in data vector
        for (int i = 0; i < v.GetLength(0); i++)
        {
          
            // Pushing the x coordinate 
            data.Add(new pair(v[i,0], 'x'));
          
            // pushing the y coordinate 
            data.Add(new pair(v[i,1], 'y'));
        }
      
        // Sorting of ranges 
        data.Sort((a,b)=>a.first - b.first);
      
        // Traverse the data vector to
        // count number of overlaps
        for (int i = 0; i < data.Count; i++)
        {
          
            // If x occur it means a new range
            // is added so we increase count
            if (data[i].second == 'x')
            {
                count++;
            }
          
            // If y occur it means a range
            // is ended so we decrease count
            if (data[i].second == 'y')
            {
                count--;
            }
          
            // Updating the value of ans
            // after every traversal 
            ans = Math.Max(ans,count);
        }
      
        // Printing the maximum value 
        Console.WriteLine(ans);
    }
  
    // Driver code
    public static void Main(String[] args)
    {
        int[,] v = {{1, 2}, {2, 4}, {3, 6}};
        GFG.overlap(v);
    }
}

// This code is contributed by aadityaburujwale.
JavaScript
// Javascript program that print maximum
// number of overlap among given ranges

// Function that print maximum
// overlap among ranges
function overlap(v)
{
    
    // Variable to store the maximum
    // count
    var ans = 0;
    var count = 0;
    var data = [];

    // Storing the x and y
    // coordinates in data vector
    for(var i = 0; i < v.length; i++) 
    {
        
        // Pushing the x coordinate
        data.push([v[i][0], 'x']);

        // Pushing the y coordinate
        data.push([v[i][1], 'y']);
    }

    // Sorting of ranges
    data.sort();

    // Traverse the data vector to
    // count number of overlaps
    for(var i = 0; i < data.length; i++) 
    {
        
        // If x occur it means a new range
        // is added so we increase count
        if (data[i][1] == 'x')
            count++;

        // If y occur it means a range
        // is ended so we decrease count
        if (data[i][1] == 'y')
            count--;

        // Updating the value of ans
        // after every traversal
        ans = Math.max(ans, count);
    }

    // Printing the maximum value
    console.log(ans + "<br>");
}

// Driver code
var v = [ [ 1, 2 ], [ 2, 4 ], [ 3, 6 ] ];
overlap(v);

// This code is contributed by rutvik_56

Output
2

Time Complexity: O(N log N), for sorting the data vector.
Auxiliary Space: O(N), for creating an additional array of size 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
Find Non-overlapping intervals among a given set of intervals
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} }
7 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
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
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
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
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
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
Maximum number of intervals that an interval can intersect
Given an array arr[] consisting of N intervals of the form of [L, R], where L, R denotes the start and end positions of the interval, the task is to count the maximum number of intervals that an interval can intersect with each other. Examples: Input: arr[] = {{1, 2}, {3, 4}, {2, 5}}Output: 3Explanation: The required set of intervals are {1, 2}, {2
15+ min read
Maximum number of overlapping string
Given two strings S and T, the task is to count the number of the overlapping string T in the string S.Note: If there are some mismatched words as a subsequence that do not match the string T, then print -1. Examples: Input: S = "chirpchirp", T = "chirp" Output: 0 Explanation: There are no overlapping strings of "chirp". Input: S = "chcirphirp", T
7 min read
Maximum number of elements without overlapping in a Line
Given two arrays X and L of same size N. Xi represent the position in an infinite line. Li represents the range up to which ith element can cover on both sides. The task is to select the maximum number of elements such that no two selected elements overlap if they cover the right or the left side segment.Note: Array X is sorted. Examples: Input : x
7 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
Maximum number of overlapping rectangles with at least one common point
Given four arrays x1[], x2[], y1[], y2[] of size N where (x1[i], y1[i]) denotes the left-bottom corner and (x2[i], y2[i]) right-top corner of a rectangle, the task is to find the maximum number of overlapping rectangles with at least one common point. Examples: Input: N = 2 x1[] = {0, 50} y1[] = {0, 50} x2[] = {100, 60} y2[] = {100, 60}Output: 2Exp
8 min read
Maximum Profit By Choosing A Subset Of Intervals (Using Priority-Queue)
Given a list intervals of n intervals, the ith element [s, e, p] denotes the starting point s, ending point e, and the profit p earned by choosing the ith interval. Find the maximum profit one can achieve by choosing a subset of non-overlapping intervals. Two intervals [s1, e1, p1] and [s2, e2, p2] are said to be non-overlapping if [e1 ? s2] and [s
8 min read
Find the point where maximum intervals overlap
Consider a big party where a log register for guest's entry and exit times is maintained. Find the time at which there are maximum guests in the party. Note that entries in register are not in any order.Example : Input: arrl[] = {1, 2, 9, 5, 5} exit[] = {4, 5, 12, 9, 12} First guest in array arrives at 1 and leaves at 4, second guest arrives at 2 a
13 min read
Find Maximum Powerful Integer with Occurrences ≥ k in 2D Intervals
Given a 2D integer array of intervals whose length is n where intervals[i]=[start, end] i.e. all integers from start to end inclusive of start and end are also present and we are given an integer k. We have to return the powerful integer. A powerful Integer is an integer that occurs atleast k times. If multiple integers have at least k occurrences,
10 min read
Kth largest even number in N intervals
Given a 2D array arr[] of N ranges, indicating integer intervals from L to R inclusive, and a number K, the task is to find Kth largest even number. Examples: Input: arr = {{12, 15}, {3, 9}, {2, 5}, {20, 25}, {16, 20}}, K = 9Output: 6Explanation: After merging, the ranges become {{2, 9}, {12, 25}} the, even numbers present in the ranges are {2, 4,
11 min read
Minimum number of intervals to cover the target interval
Given an array A[] consisting of N intervals and a target interval X, the task is to find the minimum number of intervals from the given array A[] such that they entirely cover the target interval. If there doesn't exist any such interval then print "-1". Examples: Input: A[] = {{1, 3}, {2, 4}, {2, 10}, {2, 3}, {1, 1}}, X = {1, 10}Output: 2Explanat
15+ min read
Count the number of intervals in which a given value lies
Given a 2D-array of [Tex]N [/Tex]integer intervals [Tex][L, R] [/Tex]and a value [Tex]V [/Tex]. For every interval [li, ri], the task is to check if V lies in between li and ri, both inclusive. The task is to print the count of intervals that satisfies this. Note: 1&lt;=li&lt;= riExamples: Input: arr[][] = {{1, 10}, {5, 10}, {15, 25}, {7, 12}, {20,
13 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
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
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 Sum of two non-overlapping Subarrays of any length
Given an array A consisting of N integers, the task is to find the maximum sum of two non-overlapping subarrays of any length of the array. Note: You can select empty subarrays also. Examples: Input: N = 3, A[] = {-4, -5, -2}Output: 0Explanation: Two empty subarrays are optimal with maximum sum = 0. Input: N = 5, A[] = {5, -2, 3, -6, 5}Output: 11Ex
6 min read
Maximum non overlapping Subset with sum greater than K
Given an array, arr[] and integer K, the task is to find the maximum number of non-overlapping subsets such that the sum of the subsets is strictly greater than K when you may also change the value of each element to the maximum value of the particular subset. Examples: Input: arr[]= {90, 80, 70, 60, 50, 100}, K = 180Output: 2 Input: arr[] = {3, 2,
5 min read
Maximum sum of lengths of non-overlapping subarrays with k as the max element.
Find the maximum sum of lengths of non-overlapping subarrays (contiguous elements) with k as the maximum element. Examples: Input : arr[] = {2, 1, 4, 9, 2, 3, 8, 3, 4} k = 4 Output : 5 {2, 1, 4} =&gt; Length = 3 {3, 4} =&gt; Length = 2 So, 3 + 2 = 5 is the answer Input : arr[] = {1, 2, 3, 2, 3, 4, 1} k = 4 Output : 7 {1, 2, 3, 2, 3, 4, 1} =&gt; Len
15+ min read
Maximum sum of at most K non-overlapping Subarray
Given an array, arr[] of size N, the task is to find the sum of the at most K non-overlapping contiguous subarray within an arr[] with the maximum sum. Examples: Input: arr[] = [4, 1, -3, 7, -5, 6, -2, 1], K = 3Output: 18Explanation: In the above input, the maximum k subarray sum is 18 and the subarrays are {{4, 1}, {7}, {6}} Input: arr[] = [8, -1,
15 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
K maximum sums of non-overlapping contiguous sub-arrays
Given an Array of Integers and an Integer value k, find out k non-overlapping sub-arrays which have k maximum sums. Examples: Input : arr1[] = {4, 1, 1, -1, -3, -5, 6, 2, -6, -2}, k = 3. Output : {4,1},{1} and {6,2} can be taken, thus the output should be 14. Input : arr2 = {5, 1, 2, -6, 2, -1, 3, 1}, k = 2. Output : Maximum non-overlapping sub-arr
10 min read
Article Tags :
Practice Tags :