VOOZH about

URL: https://www.geeksforgeeks.org/dsa/merging-intervals/

⇱ Merge Overlapping Intervals - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Merge Overlapping Intervals

Last Updated : 13 Aug, 2025

Given an array of time intervals where arr[i] = [starti, endi], our task is to merge all the overlapping intervals into one and output the result which should have only mutually exclusive intervals.

Examples:

Input: arr[] = [[1, 3], [2, 4], [6, 8], [9, 10]]
Output: [[1, 4], [6, 8], [9, 10]]
Explanation: In the given intervals, we have only two overlapping intervals [1, 3] and [2, 4]. Therefore, we will merge these two and return [[1, 4]], [6, 8], [9, 10]].

Input: arr[] = [[7, 8], [1, 5], [2, 4], [4, 6]]
Output: [[1, 6], [7, 8]]
Explanation: We will merge the overlapping intervals [[1, 5], [2, 4], [4, 6]] into a single interval [1, 6].

[Naive Approach] Checking All Possible Overlaps – O(n^2) Time and O(n) Space

A simple approach is to group all the intervals by sorting them then start from the first interval and compare it with all other intervals for overlaps. If the first interval 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.


Output
1 6
7 8

[Expected Approach] Checking Last Merged Interval – O(n*log(n)) Time and O(n) Space

In the previous approach, for each range we are checking for possible overlaps by iterating over all the remaining ranges till the end. We can optimize this by checking only those intervals that overlap with the last merged interval. Since the intervals will be sorted based on starting point, so if we encounter an interval whose starting time lies outside the last merged interval, then all further intervals will also lie outside it.

The intuition is to first sort the intervals based on their starting points. This allows us to easily identify overlapping intervals by comparing each interval with the last merged interval. Now, iterate over each interval and if the current interval overlaps with the last merged interval, then merge them both. Otherwise, append the merged interval to the result.


Output
1 6
7 8
Comment
Article Tags: