Merge Intervals

Inserting Intervals: Merging and Maintaining

The task of merging overlapping intervals is a frequent problem in computer science, often encountered in scheduling and timeline management scenarios.

In this article, we’ll explore how to merge intervals and return a concise, non-overlapping set that covers all the given ranges.

Problem Description

You are given an array of intervals where each interval is represented as intervals[i] = [start_i, end_i]. Your task is to merge all overlapping intervals into a single interval whenever possible and return the resulting array.

Key Points:

  1. Overlapping Definition: Two intervals overlap if their ranges have at least one common point.

    • For example:
      • [1,2] and [3,4] are non-overlapping.
      • [1,2] and [2,3] overlap, as they share the point 2.
  2. Goal: Minimize the total number of intervals by merging overlapping ones.  

Explanation:

  • [1,3] overlaps with[1,5], so they are merged into [1,5].
  • [6,7] does not overlap with any other interval, so it remains as is.

Explanation:

  • [1,2] and [2,3] overlap, so they are merged into [1,3].

Approach to Solve the Problem

To solve this problem effectively, we can use the following approach:

Step 1: Sort the Intervals

  • Sorting the intervals by their start time ensures that overlapping intervals appear consecutively in the list. This makes it easier to merge them.

Step 2: Merge Overlapping Intervals

  • Use a result list to store merged intervals.
  • Compare each interval with the last interval in the result list:
    • If they overlap, merge them by updating the end of the last interval to the maximum end time.
    • If they don’t overlap, add the current interval to the result list.

Algorithm

  1. Sort the intervals based on their start time.
  2. Initialize an empty list merged to store the result.
  3. Iterate through the sorted intervals:
    • If the current interval overlaps with the last merged interval, merge them.
    • Otherwise, add the current interval to the result list.

There are mainly three approach to solve this problem – 

  1. Sorting 
  2. Sweep Line Algorithm
  3. Greedy 

1. Sorting  

  • Time complexity: O(nlog⁡n)
  • Space complexity:  or O(n)depending on the sorting algorithm.

2. Sweep Line Algorithm

Time & Space Complexity
  • Time complexity: O(nlog n)
  • Space complexity: O(n)

Code

3. Greedy

  • Time complexity: O(n+m)
  • Space complexity: O(n)

More Articles