tutorialcup@gmail.com

Merge Overlapping Intervals

Arrays
Reverse Array
Pair Sum Equals Number
Floor and Ceil
Largest Sum Subarray
Missing Number
Odd Occuring Number
Sort by Frequency
First and Second Smallest
Majority Element
Difference between elements
Arrange Even and Odd
Closest Sum Elements
Distinct Elements
First Repeating Number
Common Elements in Arrays
Smallest Missing Number
Max Adjacent Sum
Find Occurrences of Number
Rotate Image
Distance Between Numbers
Pair with given difference
Product Array Puzzle
Replace Elements
First Repeating Element
Move Zeroes to End
Pythagorean Triplets
Maximum Average Subarray
Subarray Sum Equal to X
Leaders in Array
Largest Pair Sum
Segregate 0s 1s and 2s
Find Duplicates
Consecutive Elements Check
Triplet with given Sum
Binary Search in Sorted Array
Fixed point in sorted array
Reorder Elements by Indexes
Merging two sorted arrays
Find next greater number
Reorder array using given indexes
Count of triplets with sum less than given value
Merge two sorted arrays
Subarray and Subsequence
Rearrange array maximum minimum form
Find the lost element from a duplicated array
Count minimum steps to get the given array
Maximum element in an array which is increasing and then decreasing
Minimum number of jumps to reach the end of an array
Subarray with given sum
Length of Longest Increasing Subsequence
Smallest positive number missing unsorted array
The Celebrity Problem
Sorted subsequence of size 3
Partition Problem
Find pair with given difference
Maximum length of chain pairs
Four elements that sum to given
Maximum circular subarray sum
Count possible triangles
Longest Increasing Subsequence
Petrol Bunks Tour
Tug of War
Counting Sort
Maximum Repeating Number
Positive Negative Arrangement
Find a Peak element
Elements More Than n/k
Max Product Subsequence
Longest Bitonic subarray in an array
Number of smaller elements on right side
Implement two stacks in an array
Maximum sum increasing subsequence
Find the two numbers with odd occurrences in an unsorted array
Largest subarray with equal number of 0's and 1's
Maximum product subarray
Replace every element with the greatest on the right side in an array
Sorting a k sorted array
Find the row with maximum number of 1's
Shuffle a given array
Iterative Implementation of quick sort
Arrange given numbers to form the biggest number
Pancake sorting
Pancake sorting Problem
Maximum Subarray Sum using Divide and Conquer
Merge Overlapping Intervals
Stock Buy Sell to Maximize Profit
Sort Elements by frequency
Print all possible combinations of r elements in a given array of size n
Monotonically increasing function
Minimum element in a sorted and rotated array
Merge k Sorted Arrays
Flip Zeroes for Consecutive 1's
Least Average Subarray
Longest span with same sum in two binary arrays
Form minimum number from given sequence of D's and I's
Number of strictly increasing subarrays
Minimum difference between any two elements in an array
Number of pairs with given sum
Make Array Palindrome
Dynamic Programming, Longest Bitonic SubSequence

Given a set of intervals, this function will merge the overlapping intervals into one and prints all the non overlapping intervals

Example

INPUT:
arr[] = {{1,6},{3,9},{11,13},{2,5}}

OUTPUT:
After merging the intervals are [1,9], [11,13]

Time Complexity: O(nlogn)
Space Complexity: O(n)

Algorithm

1. Sort the Intervals based on the increasing order of start time

2. Push the first interval on to a stack

3. For each Interval

  1. If the current interval does not overlap with the stack top, push it
  2. If the current element overlaps with stack top and ending time of current interval is more     than that of stack top, update stack top with the ending time of current interval

4. Now, Stack conatins merged intervals

C++ Program

#include<bits/stdc++.h>
using namespace std;
 
// An interval has start time and end time
struct Interval
{
    int start, end;
};
 
// To compare two intervals accoridng to their start time
bool myComp(Interval interval1, Interval interval2)
{
    return (interval1.start < interval2.start);
}
 
// This function takes a set of intervals, merges
// overlapping intervals and prints the result
void mergeIntervals(Interval arr[], int n)
{
    // Test if the given set has at least one interval
    if (n <= 0)
        return;
 
    // Create an empty stack of intervals
    stack<Interval> s;
 
    // sorting the intervals in increasing order of start time
    sort(arr, arr+n, myComp);
 
    // push the first interval to stack
    s.push(arr[0]);
 
    // Start from the next interval and merge if necessary
    for (int i = 1 ; i < n; i++)
    {
        // get interval from stack top
        Interval top = s.top();
 
        // if current interval is not overlapping with stack top,
        // push it to the stack
        if (top.end < arr[i].start)
            s.push(arr[i]);
 
        // Otherwise update the ending time of top if ending of current
        // interval is more
        else if (top.end < arr[i].end)
        {
            top.end = arr[i].end;
            s.pop();
            s.push(top);
        }
    }
 
    // Print contents of stack
    cout << "\n After merging Intervals are: ";
    while (!s.empty())
    {
        Interval t = s.top();
        cout << "[" << t.start << "," << t.end << "] ";
        s.pop();
    }
    return;
}
int main()
{
	Interval arr[]= {{1,6},{3,9},{11,13},{2,5}};  //creating an array
    int n = sizeof(arr)/sizeof(arr[0]); //size of the array
    mergeIntervals(arr,n);
    return 0;
}
Try It

Time Complexity: O(nlogn)
Space Complexity: O(1)

Algorithm

1. Sort the intervals based on decreasing order of start time

2. For each Interval, starting from the first interval

  1. If the current interval is not the first interval and it overlaps with the previous interval, then merge it with previous interval. Keep doing it while the interval overlaps with the previous one.
  2. Else, add current interval to output list of intervals

C++ Program

#include<bits/stdc++.h>
using namespace std;
 
// An Interval
struct Interval
{
    int start, end;
};
 
// To compare two intervals accoridng to their start time
bool mycomp(Interval interval1, Interval interval2)
{   return interval1.start > interval2.start; }
 
void mergeIntervals(Interval arr[], int n)
{
    // Sort Intervals in decreasing order of start time
    sort(arr, arr+n, mycomp);

    // Stores index of last element in the output array
    int index = 0;

 
    // Traverse all input Intervals
    for (int i=0; i<n; i++)
    {
        // If this is not first Interval and overlaps
        // with the previous one
        if (index != 0 && arr[index-1].start <= arr[i].end)
        {
            while (index != 0 && arr[index-1].start <= arr[i].end)
            {
                // Merge previous and current Intervals
                arr[index-1].end = max(arr[index-1].end, arr[i].end);
                arr[index-1].start = min(arr[index-1].start, arr[i].start);
                index--;
            }
        }
        // Doesn't overlap with previous, add to the solution 
        else 
            arr[index] = arr[i];
 
        index++;
    }
 
    // Now arr[0..index-1] stores the merged Intervals
    cout << "\n After Merging the Intervals are: ";
    for (int i = 0; i < index; i++)
        cout << "[" << arr[i].start << ", " << arr[i].end << "] ";
}
 
// Driver program
int main()
{
    Interval arr[] = {{1,6},{3,9},{11,13},{2,5}};
    int n = sizeof(arr)/sizeof(arr[0]);
    mergeIntervals(arr, n);
    return 0;
}
Try It

 


C++ Online Test - Check Your Rank across the World


Next > < Prev
Scroll to Top