#56

Merge Intervals

Medium
ArraySortingSortingGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution sorts the intervals first and then merges them in a single pass. This is efficient because once sorted, overlapping intervals will be adjacent, allowing us to merge them easily.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the intervals by their starting times.
  2. 2Step 2: Initialize an empty list for merged intervals and add the first interval.
  3. 3Step 3: Iterate through the sorted intervals, merging them if they overlap with the last added interval.
solution.py11 lines
1def merge(intervals):
2    if not intervals:
3        return []
4    intervals.sort(key=lambda x: x[0])
5    merged = [intervals[0]]
6    for i in range(1, len(intervals)):
7        if merged[-1][1] >= intervals[i][0]:
8            merged[-1][1] = max(merged[-1][1], intervals[i][1])
9        else:
10            merged.append(intervals[i])
11    return merged

Complexity note: The sorting step takes O(n log n) time, and the merging step takes O(n) time, leading to an overall time complexity of O(n log n). Space complexity is O(n) due to the storage of merged intervals.

  • 1Sorting helps in efficiently merging overlapping intervals.
  • 2Overlapping intervals will always be adjacent after sorting.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.