Meeting Room

Merging Overlapping Intervals: Meeting Room

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:

  • (0,30) and (5,10) will conflict
  • (0,30) and (15,20) will conflict

Explanation:

  • (0,8),(8,10) is not considered a conflict at 8

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

  • Sort the intervals based on their start time.
  • Initialize an empty list merged to store the result.
  • 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. Brute Force 
  2. Sweep Line Algorithm
  3. Greedy 

1. Brute Force 

  • Time complexity: O(2^n)
  • Space complexity:  O(1)

2. Sorting 

Time & Space Complexity
  • Time complexity: O(nlogn)
  • Space complexity: O(1) or O(n) depending on the sorting algorithm.

Code

More Articles