This page was AI-generated. For the canonical problem, visit LeetCode #56.

Merge Intervals

Merge overlapping intervals using a greedy approach with sorting

Greedy LeetCode 56 ↗ Medium

Problem

Given: An array of intervals where intervals[i] = [starti, endi]

Task: Merge all overlapping intervals and return an array of non-overlapping intervals that cover all intervals in the input.

Example:

  • Input: [[1,3],[2,6],[8,10],[15,18]] → Output: [[1,6],[8,10],[15,18]]
  • Input: [[1,4],[4,5]] → Output: [[1,5]]

Visualization

Timeline Visualization
Load intervals to start visualization
Code
fun merge(intervals: Array<IntArray>): List<IntArray> {
intervals.sortBy { it[0] }
val merged = mutableListOf(intervals[0])
for (i in 1 until intervals.size) {
val current = intervals[i]
val last = merged.last()
if (current[0] <= last[1]) {
last[1] = maxOf(last[1], current[1])
} else {
merged.add(current)
}
}
return merged
}
Status & Log
Ready

Explanation

Key Insight

After sorting intervals by start time, we only need to check if the current interval overlaps with the last merged interval. If they overlap (current start ≤ last end), we extend the last interval. Otherwise, we add the current interval as a new separate interval.

Algorithm

  1. Sort: Sort all intervals by their start time
  2. Initialize: Add the first interval to the merged result
  3. Iterate: For each remaining interval:
    • If it overlaps with the last merged interval (start ≤ last end), extend the last merged interval
    • Otherwise, add it as a new interval to the result
  4. Return: The merged intervals list

Complexity Analysis

  • Time Complexity: O(n log n) where n is the number of intervals. Dominated by the sorting step.
  • Space Complexity: O(n) for the output array. If we don't count the output, it's O(1) or O(log n) depending on the sorting algorithm.