close
The Wayback Machine - https://web.archive.org/web/20241008182835/https://www.geeksforgeeks.org/merging-intervals/
Open In App

Merge Overlapping Intervals

Last Updated : 20 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 here,[1,3] and [2,4]. Therefore we will merge these two and return [1,4],[6,8], [9,10].

Input: arr = {{6,8},{1,9},{2,4},{4,7}}
Output: {{1, 9}} 

Naive O(n^2)

A simple approach is to start from the first interval and compare it with all other intervals for overlapping, if it overlaps with any other interval, then remove the other interval from the list and merge the other into the first interval. Repeat the same steps for the remaining intervals after the first. This approach cannot be implemented in better than O(n^2) time.

Using Sort

To solve this problem optimally we have to first sort the intervals according to the starting time. Once we have the sorted intervals, we can combine all intervals in a linear traversal. The idea is, in sorted array of intervals, if arr[i] doesn’t overlap with arr[i-1], then arr[i+1] cannot overlap with arr[i-1] because starting time of arr[i+1] must be greater than or equal to arr[i].

Follow the steps mentioned below to implement the approach:

  • Sort the intervals based on the increasing order of starting time.
  • Push the first interval into a stack.
  • For each interval do the following:
    • If the current interval does not overlap with the top of the stack then, push the current interval into the stack.
    • If the current interval overlap with the top of the stack then, update the stack top with the ending time of the current interval.
  • The end stack contains the merged intervals. 

Below is the implementation of the above approach:

C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

vector<vector<int>> mergeOverlap(vector<vector<int>>& arr) {

    // Sort intervals based on start values
    sort(arr.begin(), arr.end());
  
    vector<vector<int>> res;
    res.push_back(arr[0]);

    for (int i = 1; i < arr.size(); i++) {
        vector<int>& last = res.back();
        vector<int>& curr = arr[i];

        // If current overlaps with the last
        // merged, merge them 
        if (curr[0] <= last[1]) 
            last[1] = max(last[1], curr[1]);
            
        else // Add current to the result
            res.push_back(curr);
    }

    return res;
}

// Driver Code
int main() {
    vector<vector<int>> arr = {{6, 8}, {1, 9}, {2, 4}, {4, 7}};
    vector<vector<int>> res = mergeOverlap(arr);

    cout << "The Merged Intervals are: ";
    for (const vector<int>& interval : res) {
        cout << "[" << interval[0] << ", " << interval[1] << "] ";
    }
    cout << endl;

    return 0;
}
Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {

    public static List<int[]> mergeOverlap(int[][] arr) {
      
        // Sort intervals based on start values
        Arrays.sort(arr, (a, b) -> Integer.compare(a[0], b[0]));

        List<int[]> res = new ArrayList<>();
        res.add(arr[0]);

        for (int i = 1; i < arr.length; i++) {
            int[] last = res.get(res.size() - 1);
            int[] curr = arr[i];

            // If current overlaps with the last merged, merge them
            if (curr[0] <= last[1]) {
                last[1] = Math.max(last[1], curr[1]);
            } else {
                // Add current to the result
                res.add(curr);
            }
        }

        return res;
    }

    // Driver Code
    public static void main(String[] args) {
        int[][] arr = {{6, 8}, {1, 9}, {2, 4}, {4, 7}};
        List<int[]> res = mergeOverlap(arr);

        System.out.print("The Merged Intervals are: ");
        for (int[] interval : res) {
            System.out.print("[" + interval[0] + ", " + interval[1] + "] ");
        }
        System.out.println();
    }
}
Python
def merge_overlap(arr):
    # Sort intervals based on start values
    arr.sort(key=lambda x: x[0])

    res = [arr[0]]

    for i in range(1, len(arr)):
        last = res[-1]
        curr = arr[i]

        # If current overlaps with the last
        # merged, merge them
        if curr[0] <= last[1]:
            last[1] = max(last[1], curr[1])
        else:
            # Add current to the result
            res.append(curr)

    return res

# Driver Code
if __name__ == "__main__":
    arr = [[6, 8], [1, 9], [2, 4], [4, 7]]
    res = merge_overlap(arr)

    print("The Merged Intervals are: ", end="")
    for interval in res:
        print(f"[{interval[0]}, {interval[1]}]", end=" ")
    print()
C#
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    public static List<int[]> MergeOverlap(int[][] arr)
    {
        // Sort intervals based on start values
        Array.Sort(arr, (a, b) => a[0].CompareTo(b[0]));

        List<int[]> res = new List<int[]>();
        res.Add(arr[0]);

        for (int i = 1; i < arr.Length; i++)
        {
            int[] last = res[res.Count - 1];
            int[] curr = arr[i];

            // If current overlaps with the last merged, merge them
            if (curr[0] <= last[1])
            {
                last[1] = Math.Max(last[1], curr[1]);
            }
            else
            {
                // Add current to the result
                res.Add(curr);
            }
        }

        return res;
    }

    // Driver Code
    static void Main(string[] args)
    {
        int[][] arr = new int[][] {
            new int[] { 6, 8 },
            new int[] { 1, 9 },
            new int[] { 2, 4 },
            new int[] { 4, 7 }
        };

        List<int[]> res = MergeOverlap(arr);

        Console.Write("The Merged Intervals are: ");
        foreach (int[] interval in res)
        {
            Console.Write("[" + interval[0] + ", " + interval[1] + "] ");
        }
        Console.WriteLine();
    }
}
JavaScript
function mergeOverlap(arr) {

    // Sort intervals based on start values
    arr.sort((a, b) => a[0] - b[0]);

    let res = [arr[0]];

    for (let i = 1; i < arr.length; i++) {
        let last = res[res.length - 1];
        let curr = arr[i];

        // If current overlaps with the last 
        // merged, merge them
        if (curr[0] <= last[1]) {
            last[1] = Math.max(last[1], curr[1]);
        } else {
            // Add current to the result
            res.push(curr);
        }
    }

    return res;
}

// Driver Code
let arr = [[6, 8], [1, 9], [2, 4], [4, 7]];
let res = mergeOverlap(arr);

console.log("The Merged Intervals are:");
res.forEach(interval => {
    console.log(`[${interval[0]}, ${interval[1]}]`);
});

Output
The Merged Intervals are: [1, 9] 

Time complexity: O(n log n)
Auxiliary Space: O(n)

In-Place Using Sort

The above solution requires O(n) extra space for the stack. We can avoid the use of extra space by doing merge operations in place. Below are detailed steps. 

Follow the steps mentioned below to implement the approach:

  • Sort all intervals in increasing order of start time.
  • Traverse sorted intervals starting from the first interval, 
  • Do the following for every interval.
    • If the current interval is not the first interval and it overlaps with the previous interval,
       then merge it with the previous interval. Keep doing it while the interval overlaps with the previous one.         
    •  Otherwise, Add the current interval to the output list of intervals.

Below is the implementation of the above approach:

C++14
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

// Merge overlapping intervals in-place. We return
// modified size of the array arr.
int mergeOverlap(vector<vector<int>>& arr) {

    // Sort intervals based on start values
    sort(arr.begin(), arr.end());

    int resIdx = 0; // Index of the last merged 

    for (int i = 1; i < arr.size(); i++) {
      
        // If current interval overlaps with the 
        // last merged interval
        if (arr[resIdx][1] >= arr[i][0])           
            arr[resIdx][1] = max(arr[resIdx][1], arr[i][1]);
      
        // Move to the next interval
        else {            
            resIdx++;
            arr[resIdx] = arr[i];
        }
    }

    // Returns size of the merged intervals
    return (resIdx + 1);
}

// Driver Code
int main() {
    vector<vector<int>> arr = {{6, 8}, {1, 9}, {2, 4}, {4, 7}};
    
    // Get the new size of the array after merging
    int newSize = mergeOverlap(arr);

    // Print the merged intervals based on the new size
    cout << "The Merged Intervals are: ";
    for (int i = 0; i < newSize; i++) {
        cout << "[" << arr[i][0] << ", " << arr[i][1] << "] ";
    }
    cout << endl;

    return 0;
}
C
// C program to merge overlapping Intervals in
// O(n Log n) time and O(1) extra space.
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

// An Interval
typedef struct Interval {
    int s, e;
} Interval;

// Function used in sort
int mycomp(const void* a, const void* b)
{
    Interval* data_1 = (Interval*)a;
    Interval* data_2 = (Interval*)b;
    return (data_1->s - data_2->s);
}

// Find maximum between two numbers.
int max(int num1, int num2)
{
    return (num1 > num2) ? num1 : num2;
}

void mergeIntervals(Interval arr[], int n)
{
    // Sort Intervals in increasing order of
    // start time
    qsort(arr, n, sizeof(Interval), mycomp);

    int index = 0; // Stores index of last element
    // in output array (modified arr[])

    // Traverse all input Intervals
    for (int i = 1; i < n; i++) {
      
        // If this is not first Interval and overlaps
        // with the previous one
        if (arr[index].e >= arr[i].s) {
            // Merge previous and current Intervals
            arr[index].e = max(arr[index].e, arr[i].e);
        }
        else {
            index++;
            arr[index] = arr[i];
        }
    }

    // Now arr[0..index-1] stores the merged Intervals
    printf("\n The Merged Intervals are: ");
    for (int i = 0; i <= index; i++)
        printf("[%d, %d]", arr[i].s, arr[i].e);
}

// Driver program
int main()
{
    Interval arr[]
        = { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } };
    int n = sizeof(arr) / sizeof(arr[0]);
    mergeIntervals(arr, n);
    return 0;
}

// This code is contributed by Aditya Kumar (adityakumar129)
Java
import java.util.Arrays;

public class Main {

    // Merge overlapping intervals in-place and return
    // the new size of the array
    public static int mergeOverlap(int[][] arr) {
       
        // Sort intervals based on start values
        Arrays.sort(arr, (a, b) -> Integer.compare(a[0], b[0]));

        int resIdx = 0; // Index of the last merged interval

        for (int i = 1; i < arr.length; i++) {
          
            // If current interval overlaps with the last merged interval
            if (arr[resIdx][1] >= arr[i][0]) {
                arr[resIdx][1] = Math.max(arr[resIdx][1], arr[i][1]);
            } else {
                // Move to the next interval
                resIdx++;
                arr[resIdx] = arr[i];
            }
        }

        // Return the size of the merged intervals
        return resIdx + 1;
    }

    // Driver Code
    public static void main(String[] args) {
        int[][] arr = { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } };

        // Get the new size of the array after merging
        int newSize = mergeOverlap(arr);

        // Print the merged intervals based on the new size
        System.out.print("The Merged Intervals are: ");
        for (int i = 0; i < newSize; i++) {
            System.out.print("[" + arr[i][0] + ", " + arr[i][1] + "] ");
        }
        System.out.println();
    }
}
Python
def merge_overlap(arr):
    # Sort intervals based on start values
    arr.sort(key=lambda x: x[0])

    res_idx = 0  # Index of the last merged interval

    for i in range(1, len(arr)):
      
        # If current interval overlaps with 
        # the last merged interval
        if arr[res_idx][1] >= arr[i][0]:
            arr[res_idx][1] = max(arr[res_idx][1], arr[i][1])
        else:
            # Move to the next interval
            res_idx += 1
            arr[res_idx] = arr[i]

    # Return the size of the merged intervals
    return res_idx + 1

# Driver Code
if __name__ == "__main__":
    arr = [[6, 8], [1, 9], [2, 4], [4, 7]]

    # Get the new size of the array after merging
    new_size = merge_overlap(arr)

    # Print the merged intervals based on the new size
    print("The Merged Intervals are:", end=" ")
    for i in range(new_size):
        print(f"[{arr[i][0]}, {arr[i][1]}]", end=" ")
    print()
C#
using System;
using System.Collections.Generic;

public class GfG
{
    public static int MergeOverlap(int[][] arr)
    {
        // Sort intervals based on start values
        Array.Sort(arr, (a, b) => a[0].CompareTo(b[0]));

        int resIdx = 0; // Index of the last merged interval

        for (int i = 1; i < arr.Length; i++)
        {
            // If current interval overlaps with the last merged interval
            if (arr[resIdx][1] >= arr[i][0])
            {
                arr[resIdx][1] = Math.Max(arr[resIdx][1], arr[i][1]);
            }
            else
            {
                // Move to the next interval
                resIdx++;
                arr[resIdx] = arr[i];
            }
        }

        // Return the size of the merged intervals
        return resIdx + 1;
    }

    public static void Main()
    {
        int[][] arr = new int[][] {
            new int[] { 6, 8 },
            new int[] { 1, 9 },
            new int[] { 2, 4 },
            new int[] { 4, 7 }
        };

        // Get the new size of the array after merging
        int newSize = MergeOverlap(arr);

        // Print the merged intervals based on the new size
        Console.WriteLine("The Merged Intervals are:");
        for (int i = 0; i < newSize; i++)
        {
            Console.WriteLine("[" + arr[i][0] + ", " + arr[i][1] + "]");
        }
    }
}
JavaScript
function mergeOverlap(arr) {
    // Sort intervals based on start values
    arr.sort((a, b) => a[0] - b[0]);

    let resIdx = 0; // Index of the last merged interval

    for (let i = 1; i < arr.length; i++) {
    
        // If current interval overlaps with the last merged interval
        if (arr[resIdx][1] >= arr[i][0]) {
            arr[resIdx][1] = Math.max(arr[resIdx][1], arr[i][1]);
        } else {
            // Move to the next interval
            resIdx++;
            arr[resIdx] = arr[i];
        }
    }

    // Return the size of the merged intervals
    return resIdx + 1;
}

// Driver Code
const arr = [[6, 8], [1, 9], [2, 4], [4, 7]];

// Get the new size of the array after merging
const newSize = mergeOverlap(arr);

// Print the merged intervals based on the new size
console.log("The Merged Intervals are:");
for (let i = 0; i < newSize; i++) {
    console.log(`[${arr[i][0]}, ${arr[i][1]}]`);
}

Output
 The Merged Intervals are: [1, 9] 

Time Complexity: O(n log n)
Auxiliary Space Complexity: O(1)



Similar Reads

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
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
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 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 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
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
Add minimum sized interval such that all intervals merge into one
Given a 2D array arr of size N which represents an interval [start, end] inclusive where (start < end), the task is to add only one interval of minimum size (size = end - start) into the given arr, such that merging all the interval result in only one interval. Examples: Input: arr= {{12, 20}, {24, 100}}Output: 4Explanation: We can add the inter
8 min read
Merge Sort with O(1) extra space merge and O(n log n) time [Unsigned Integers Only]
We have discussed Merge sort. How to modify the algorithm so that merge works in O(1) extra space and algorithm still works in O(n Log n) time. We may assume that the input values are integers only. Examples: Input : 5 4 3 2 1 Output : 1 2 3 4 5 Input : 999 612 589 856 56 945 243 Output : 56 243 589 612 856 945 999Recommended PracticeMerge SortTry
10 min read
Merge operations using STL in C++ | merge(), includes(), set_union(), set_intersection(), set_difference(), ., inplace_merge,
Some of the merge operation classes are provided in C++ STL under the header file "algorithm", which facilitates several merge operations in a easy manner. Some of them are mentioned below. merge(beg1, end1, beg2, end2, beg3) :- This function merges two sorted containers and stores in new container in sorted order (merge sort). It takes 5 arguments
7 min read
Find Intersection of all Intervals
Given N intervals of the form of [l, r], the task is to find the intersection of all the intervals. An intersection is an interval that lies within all of the given intervals. If no such intersection exists then print -1. Examples: Input: arr[] = {{1, 6}, {2, 8}, {3, 10}, {5, 8}} Output: [5, 6] [5, 6] is the common interval that lies in all the giv
5 min read
Maximal Disjoint Intervals
Given a set of N intervals, the task is to find the maximal set of mutually disjoint intervals. Two intervals [i, j] & [k, l] are said to be disjoint if they do not have any point in common. Examples: Input: intervals[][] = {{1, 4}, {2, 3}, {4, 6}, {8, 9}} Output: [2, 3] [4, 6] [8, 9] Intervals sorted w.r.t. end points = {{2, 3}, {1, 4}, {4, 6}
6 min read
Find intersection of intervals given by two lists
Given two 2-D arrays which represent intervals. Each 2-D array represents a list of intervals. Each list of intervals is disjoint and sorted in increasing order. Find the intersection or set of ranges that are common to both the lists. Disjoint means no element is common in a list. Example: {1, 4} and {5, 6} are disjoint while {1, 4} and {2, 5} are
7 min read
Kth smallest element from an array of intervals
Given an array of intervals arr[] of size N, the task is to find the Kth smallest element among all the elements within the intervals of the given array. Examples: Input : arr[] = {{5, 11}, {10, 15}, {12, 20}}, K =12Output: 13Explanation: Elements in the given array of intervals are: {5, 6, 7, 8, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 1
7 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
Count intervals that intersects with a given meeting time
Given an array arr[][2] consisting of N pair of strings representing the starting and ending time (in 12 hours format) and a string P which represents the time of the meeting, the task is to find the count of intervals that contains the time P. Examples: Input: P = “12:01:AM”, arr[][2] = {{“12:00:AM”, “11:55:PM”}, {“12:01:AM”, “11:50:AM”}, {“12:30:
9 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
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
Minimum Set size for covering intervals
Given an array arr[] consisting of N ranges of the form [L, R], the task is to determine the size of the smallest set that contains at least 2 integers within each interval. Examples: Input: arr[] = { {1, 3}, {2, 5}, {1, 4} }Output: 2Explanation: Interval [1, 3] contains the numbers 1, 2, 3.Interval [2, 5] contains the numbers 2, 3, 4, 5.Interval [
7 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
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
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<=li<= riExamples: Input: arr[][] = {{1, 10}, {5, 10}, {15, 25}, {7, 12}, {20,
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
Minimum distance to travel to cover all intervals
Given many intervals as ranges and our position. We need to find minimum distance to travel to reach such a point which covers all the intervals at once. Examples: Input : Intervals = [(0, 7), (2, 14), (4, 6)] Position = 3 Output : 1 We can reach position 4 by travelling distance 1, at which all intervals will be covered. So answer will be 1 Input
8 min read
Remove Interval from Disjoint Intervals
Given a sorted list of disjoint intervals representing a set of real numbers and an interval toBeRemoved to remove. The task is to remove toBeRemoved interval from the set and return the remaining intervals as a sorted list. Example: Input: intervals = {{0,2},{3,4},{5,7}}, toBeRemoved = {1,6}Output: {{0,1},{6,7}} Input: intervals = {{0,5}}, toBeRem
7 min read
Count points covered by given intervals
Consider an infinite x-y plane. Infinite people walk on the plane in an upward or +ve Y direction. At each integer point on the x-axis, only one person walks. Suppose, several barriers exist parallel to the x-axis. Barriers are provided as three triplets X1 - the x-point at which the barrier startsX2 - the x-point at which the barrier ends.Y - the
7 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
Article Tags :
Practice Tags :