#56

Merge Intervals

MediumIntervalsHas vizArraySortingInterval

Problem

Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

Example 1

Input: intervals = [[1,3],[2,6],[8,10],[15,18]]

Output: [[1,6],[8,10],[15,18]]

[1,3] and [2,6] overlap, so merge to [1,6].

Example 2

Input: intervals = [[1,4],[4,5]]

Output: [[1,5]]

Intervals that touch are considered overlapping.

Constraints

  • 1 <= intervals.length <= 10^4
  • intervals[i].length == 2
  • 0 <= starti <= endi <= 10^4
Loading visualization…

Explanation

Merge Intervals is a Medium interview problem tagged [Array, Sorting, Interval]. The winning approach is typically **Intervals**.

Intuition

Ordering makes overlaps adjacent and trivial to detect.

Approach

Sort intervals by start (or end), then merge or sweep with a counter/heap.

  1. Sort.
  2. Compare current.start with last.end.
  3. Merge or count rooms/arrows.
  4. Push new interval when disjoint.

Solution

Pattern-level skeleton only — not this problem’s exact answer. Adapt it to the statement.

Pattern templateIntervals

Edge cases

  • •Empty or single-element input
  • •Duplicates and ties
  • •Maximum constraints / overflow
  • •Disconnected or unreachable states (for graphs)

Complexity

Time: O(n log n) or O(n)

Space: O(n)

Before coding, restate the problem, name the pattern (Intervals), and write the invariant or DP state in one sentence.

Learn the topic

Got it?

Mark #56 Merge Intervals as understood when the pattern clicks.