AlgoMaster Logo

Merge Intervals

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force - Comparing All Intervals

Intuition:

The simplest, although not the most efficient, way to solve the problem is to compare each interval with every other interval to check for any overlapping. If two intervals overlap, they are merged into one. This process continues until we can no longer find any new intervals to merge, indicating all possible merges have been completed.

Steps:

  1. Iterate over every interval and check with all other intervals whether they overlap.
  2. If two intervals overlap, merge them and replace in the original list.
  3. Continue this until no more merges can occur.

Code:

2. Sort and Merge

Intuition:

A more optimal way to tackle the problem is to take advantage of sorting. By sorting intervals based on the start time, we can efficiently check for overlaps by comparing each interval with the last interval in a merged list. If they overlap, merge them; otherwise, just add the interval to the merged list.

Steps:

  1. Sort the list of intervals based on the starting time.
  2. Iterate through sorted intervals.
  3. Compare the current interval with the last merged interval:
    • If they overlap, merge them.
    • If not, simply add the current interval to the result.

Code: