Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Merge All Overlapping Intervals

Moderate
0/80
profile
Contributed by
119 upvotes

Problem statement

Ninja is playing with intervals. He has an array of intervals called โ€˜Arrโ€™ having โ€˜Nโ€™ intervals.


However, he doesnโ€™t like overlapping intervals. So you must help Ninja by merging all the overlapping intervals in โ€˜Arrโ€™ and return an array of non-overlapping intervals.


Note:
Two intervals [L1, R1] and [L2, R2] such that L1 <= L2, are said to be overlapping if and only if L2 <= R1.
For example:
For โ€˜Nโ€™ = 4, and 
โ€˜Arrโ€™ = {{1, 3}, {2, 4}, {3, 5}, {6, 7}}
We can see that {1, 3} and {2, 4} overlap, so if we merge them, we get {1, 4}.
Now โ€˜Arrโ€™ becomes: {{1, 4}, {3, 5}, {6, 7}}
Still, we observe that {1, 4} and {3, 5} overlap, hence we merge them into {1, 5}.
Hence, โ€˜Arrโ€™ becomes {{1, 5}, {6, 7}}.
Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line contains an integer โ€˜Nโ€™, denoting the size of โ€˜Arrโ€™. 
The next โ€˜Nโ€™ lines contain two integers โ€˜Lโ€™ and โ€˜Rโ€™ each, denoting the interval [L, R] in โ€˜Arrโ€™.
Output Format:
You must return an array of non-overlapping intervals after merging all the overlapping intervals of โ€˜Arrโ€™. The system will print the returned array sorted in increasing order of โ€˜Lโ€™.
Sample Input 1:
9
1 2
1 3
1 6
3 4
4 4
4 5
5 5
6 6
6 6
Sample Output 1 :
1 6
Explanation Of Sample Input 1:
Arr after each merge
{{1, 2}, {1, 3}, {1, 6}, {3, 4}, {4, 4}, {4, 5}, {5, 5}, {6, 6}, {6, 6}}
{{1, 3}, {1, 6}, {3, 4}, {4, 4}, {4, 5}, {5, 5}, {6, 6}, {6, 6}}
{{1, 6}, {3, 4}, {4, 4}, {4, 5}, {5, 5}, {6, 6}, {6, 6}}
{{1, 6}, {4, 4}, {4, 5}, {5, 5}, {6, 6}, {6, 6}}
{{1, 6}, {4, 5}, {5, 5}, {6, 6}, {6, 6}}
{{1, 6}, {5, 5}, {6, 6}, {6, 6}}
{{1, 6}, {6, 6}, {6, 6}}
{{1, 6}, {6, 6}}
{{1, 6}}
Sample Input 2:
7
2 2
2 3
2 5
3 6
4 4
4 5
6 6
Sample Output 2:
2 6
Constraints:
1 <= N <= 10^5
1 <= L <= R <= 10^9

Time Limit: 1 sec.
Hint

Try comparing all pairs of intervals.

Approaches (2)
Brute Force

Approach:

  • We create another array โ€˜Ansโ€™, which will store the non-overlapping intervals. We will traverse the array and for each interval, first, we will push the current interval to โ€˜Ansโ€™ and then we will check if this interval overlaps with any of the intervals in โ€˜Ansโ€™. If the interval overlaps with any intervals in โ€˜Ansโ€™, we will compare the starting and ending points of both intervals.
  • Likewise, we will get the least starting and maximum ending points. Then, we will iterate over โ€˜Ansโ€™ and update all the overlapping intervals with the least starting and maximum ending points. Lastly, we will iterate over โ€˜Ansโ€™, and if the current interval occurs more than once, we will delete the current occurrence.
     

Algorithm:

  • Create an empty array called โ€˜Ansโ€™.
  • for โ€˜iโ€™ from 0 to โ€˜N - 1โ€™:
    • insert โ€˜Arr[i]โ€™ in โ€˜Ansโ€™
    • Least = Arr[i][0], Max = Arr[i][1]
    • for interval โ€˜xโ€™ in โ€˜Ansโ€™:
      • if x overlaps with โ€˜Arr[i]โ€™
        • Least = min(Least, x[0])
        • Max = max(Max, x[1])
    • for interval โ€˜xโ€™ in โ€˜Ansโ€™:
      • if x overlaps with โ€˜Arr[i]โ€™:
        • x[0] = Least
        • x[1] = Max
  • p = 0
  • while(p is less than the size of โ€˜Ansโ€™):
    • Frequency = 0
    • for interval โ€˜xโ€™ in โ€˜Ansโ€™:
      • if(x == Ans[p])
        • Frequency++
    • if(Frequency > 1):
      • delete Ans[p]
    • else
      • p++
  • return โ€˜Ansโ€™.
Time Complexity

O(N ^ 2), where โ€˜Nโ€™ is the size of โ€˜Arrโ€™.
 

We are iterating over โ€˜Arrโ€™ and for each interval, we are iterating over โ€˜Ansโ€™, which can have O(N) elements. Hence, the overall time complexity of this solution is O(N * N).

Space Complexity

O(1)

 

As we are not utilizing any extra space, the overall space complexity of this solution is O(1).

Code Solution
(100% EXP penalty)
Merge All Overlapping Intervals
All tags
Sort by
Search icon

Interview problems

C++ Optimal solution || 100% better than others

 

#include<vector>

 

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

    // Write your code here.

    int n=arr.size();

    sort(arr.begin(),arr.end());

 

    vector<vector<int>>  ans;

    for(int i=0;i<n;i++)

    {

       if(ans.empty() || arr[i][0] > ans.back()[1])

       {

           ans.push_back(arr[i]);

       }

       else{

           ans.back()[1]=max(ans.back()[1],arr[i][1]);

       }

    }

    return ans;

    

}

9 views
0 replies
0 upvotes

Interview problems

JAVA || All Test Cases Passed || Easy Code

import java.util.*;

import java.util.PriorityQueue;

 

public class Solution {

    public static List< List< Integer > > mergeOverlappingIntervals(int [][]arr){

        // Write your code here.

        List<List<Integer>> list = new ArrayList<>();

        int i=0,j=1;

        for(i=0;i<arr.length;i++){

            List<Integer> list1 = new ArrayList<>();

            list1.add(arr[i][0]);

            list1.add(arr[i][1]);

            list.add(list1);

        }

        i=0;

        Collections.sort(list,(a,b)->a.get(0)==b.get(0)?a.get(1)-b.get(1):a.get(0)-b.get(0));

        while(i<j && j<list.size()){

            List<Integer> l1 = list.get(i); 

            List<Integer> l2 = list.get(j);

            if(l1.get(1)>=l2.get(0) && l1.get(1)>=l2.get(1)){

                list.remove(j);

            }else if(l1.get(1)>=l2.get(0) && l1.get(1)<=l2.get(1)){

                l1.set(1,l2.get(1));

                list.set(i,l1);

                list.remove(j);

            }else{

                i++;

                j++;

            }

        }

        return list;

    }

}

beginners

java

programming

11 views
0 replies
0 upvotes

Interview problems

C++ | Optimal Solution

#include<vector>

 

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

    // Write your code here.

    int n = arr.size();

    sort(arr.begin(), arr.end());

    vector<vector<int>> ans;

    for(int i = 0;i < n;i++){

        if(ans.empty() || arr[i][0] > ans.back()[1]){

            ans.push_back(arr[i]);

        }

        else{

            ans.back()[1] = max(ans.back()[1] , arr[i][1]);

        }

    }

    return ans;

}

10 views
0 replies
0 upvotes

Interview problems

Merge All Overlapping Intervals || Java || Optimal - O(N)

public static List< List< Integer > > mergeOverlappingIntervals(int [][]arr){

        

        int n = arr.length;

        int l1 = arr[0][0];

        int r1 = arr[0][1];

        List<List<Integer>> anslist = new ArrayList<>();

        for(int i=0; i<n; i++){

            int l2 = arr[i][0];

            int r2 = arr[i][1];

            if(l2<=r1){

                r1 = Math.max(r2, r1);

            }

            else{

                anslist.add(Arrays.asList(l1, r1));

                l1 = l2;

                r1 = r2;

            }

        }

        anslist.add(Arrays.asList(l1, r1));

 

        return anslist;  

    }

21 views
0 replies
0 upvotes

Interview problems

๐ŸŒŸ Efficient Interval Merging: Sort, Merge, and Simplify! ๐Ÿ”—๐Ÿ“…

Intuition ๐ŸŒŸ

The goal is to merge overlapping intervals from a list. To achieve this:

Sorting ๐Ÿ“…:

  • By sorting the intervals based on their start times, you align overlapping intervals next to each other. This simplifies the merging process because you only need to compare adjacent intervals.

Merging ๐Ÿ”—:

  • Once sorted, iterate through the intervals and merge any that overlap. If an interval overlaps with the current interval being considered, extend the end of the current interval. If it doesnโ€™t overlap, finalize the current interval and start a new one.
Approach ๐ŸŒŸ

Sort Intervals ๐Ÿ“Š:

  • Sort the intervals by their start time. This way, if intervals overlap, they will be next to each other in the sorted list.

Initialize Merging Process ๐Ÿ”„:

  • Start with the first interval and initialize a list to store the merged intervals.

Iterate and Merge ๐Ÿ”—:

  • Traverse through the sorted list of intervals.
  • Compare each interval with the current interval being processed:
    • If Overlapping: Extend the end of the current interval to cover the new interval.
    • If Not Overlapping: Finalize the current interval, add it to the result list, and start a new interval.

Convert to Result Format ๐Ÿ”ข:

  • Convert the list of merged intervals to a 2D array before returning it.
Complexity ๐Ÿงฎ
  • Time Complexity: O(nlogn)
    • Sorting the intervals takes O(nlogโกn)
    • Merging intervals takes O(n)
  • Space Complexity: O(n)
    • Space is used to store the merged intervals in a list.

 

 

import java.util.*;

public class Solution {
    public static List< List< Integer > > mergeOverlappingIntervals(int [][]arr){
        // Write your code here.
        int n=arr.length;

        if(n==0)
        return new ArrayList<>();
        List<int[]>ans=new ArrayList<>();
        int [] currinter=arr[0];
        ans.add(currinter);

        for(int i=1;i<n;i++)
        {
            int currstart=currinter[0];
            int currend=currinter[1];
            int nextstart=arr[i][0];
            int nextend=arr[i][1];
            if(currend>=nextstart)
            {
                currinter[1]=Math.max(currend,nextend);

            }
            else{
                currinter=arr[i];
                ans.add(currinter);
            }

        }


            List<List<Integer>> result = new ArrayList<>();
        for (int[] interval : ans) {
            result.add(Arrays.asList(interval[0], interval[1]));
        }

       return result;


    }
}
8 views
0 replies
0 upvotes

Interview problems

Easisest and shortest C++ solution

#include<vector>

vector<vector<int>> mergeOverlappingIntervals(vector<vector<int>> &arr){
	// Write your code here.
	int n = arr.size(); 
    vector<vector<int>> ans;
    for (int i = 0; i < n; i++) { 
        if(ans.empty() || arr[i][0]>ans.back()[1]) ans.push_back(arr[i]);
        else ans.back()[1]=max(ans.back()[1],arr[i][1]);
    }
    return ans;
}
19 views
0 replies
1 upvote

Interview problems

BEST CPP SOLUTION

#include<vector>

 

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

    int n = arr.size();

    sort(arr.begin(), arr.end());

    vector<vector<int>> ans;

 

    for(int i = 0; i < n ; i++){

 

          if (ans.empty() || arr[i][0] > ans.back()[1]) {

            ans.push_back(arr[i]);

          }

          else {

              ans.back()[1] = max(ans.back()[1] , arr[i][1] );

          }

        }

 

        return ans;

    

}

11 views
0 replies
0 upvotes

Interview problems

C++ Solution . Time Complexity O(n + n log n(sort)) Space Complexity O(n)

#  In this Code we will enter the first pair of sub-intervals in the ans vector. Then compare the next pair whether it is overlapping or not . 

To compare this , if the first unit of the pair is greater than the last unit of the pair that is in the ans vector , then it will surely be our new answer . So we have to add this in ans Vector.

But if the first unit of the pair is lesser than or equal to the last unit of the pair in the ans vector , then it surely be a part of the Overlapping , We have merge it with the existing overlapping , and change its last value to the maximum of two pairs.

  

 

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

    int n = arr.size();

    sort(arr.begin(),arr.end());

    vector<vector<int>> ans;

    for(int i = 0 ; i<n ; i++){

        if(ans.empty() || arr[i][0] > ans.back()[1]){

            ans.push_back(arr[i]);

        }

        else{

            ans.back()[1] = max(ans.back()[1], arr[i][1]);

        }

    }

    return ans;

}

7 views
0 replies
1 upvote

Interview problems

Merge All Overlapping Intervals

steps to solve the current problem

 

Sorting:- The intervals are first sorted by their starting times.

create a vector array.

use a for loopโ€ฆ start with int i =0 to n.

 

taking two condition 

  1. when  the vector array is empty or new subarray has to be taken .
  2. when we have a subset and which has to be extended the overlapping..

lastly return the ans.

 

code given belowโ€ฆ.

 

 

#include <bits/stdc++.h>

#include<vector>

 

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

    vector<vector<int>>ans;

    sort(arr.begin(),arr.end());

    for(int i = 0; i<arr.size();i++){

        if(ans.empty() || arr[i][0]>ans.back()[1]){

            ans.push_back(arr[i]);

        }else{

            ans.back()[1] = max(arr[i][1],ans.back()[1]);

        }

    }

    return ans;

    

}

 

 

 

 

 

14 views
0 replies
0 upvotes

Interview problems

MOST EASY TO UNDERSTAND || W/ COMMENTS

#include<vector>

 

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

    

    vector<vector<int>> ans;

    int n=arr.size();

    for(int i=0;i<n;i++){

        int start=arr[i][0]; //take start as the current element

        int end=arr[i][1]; //take end of the current element

        if(!ans.empty() and end<=ans.back()[1]){ //if the current interval already lying in the interval answered before

            continue;

        }

        for(int j=i+1;j<n;j++){ //for the ith element check from the 2nd element from it

            if(arr[j][0]<=end){ //in the next element from the current element ,cause j is i+1,if the start of the jth element is <= current's end 

                end=max(end,arr[j][1]); // then we need to get the greater end interval 

            }else{

                break; 

            }

        }

        ans.push_back({start,end});

    }

    return ans;

    

}

programming

datastructures

34 views
0 replies
0 upvotes
Full screen
Console