ToolMight Logo
MediumArrays & HashingInterval SortingGreedy Overlap Merging

Merge Intervals

Merge all overlapping intervals into sorted non-overlapping ranges. Compare graph component grouping against sorting by start time + greedy scan.

Optimal Time
O(n log n)
Optimal Space
O(n)
Primary Pattern
Interval Sorting
Visualizer
Open Interactive View →

Problem Statement

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

Examples & Constraints

Example 1
Input: intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]
Output: [[1, 6], [8, 10], [15, 18]]
Explanation: Since intervals [1, 3] and [2, 6] overlap, merge them into [1, 6].
Example 2
Input: intervals = [[1, 4], [4, 5]]
Output: [[1, 5]]
Explanation: Intervals [1, 4] and [4, 5] touch at 4, so they are considered overlapping.
Constraints
  • 1 <= intervals.length <= 10^4
  • intervals[i].length == 2
  • 0 <= start_i <= end_i <= 10^4

Pattern Recognition & Core Invariant

How to Spot This Pattern

Questions involving colliding time windows, meeting schedules, or range unions almost always simplify once intervals are sorted by start time.

Core Invariant

After sorting by start_i, any interval overlapping the active merged range must appear immediately next and extend end to max(last.end, curr.end).

Solution Approaches & Complexity

ApproachTimeSpaceNotes
1. Overlap Graph & Connected Components (Baseline)
O(n²)O(n²)Model each interval as a graph node with an edge whenever two intervals overlap, then merge every connected component into [minStart, maxEnd].
2. Sort by Start Time & Greedy MergeOptimal
O(n log n)O(n)Sort intervals in ascending order by start time. Iterate through intervals: if the current interval starts before or at the previous end time, merge them by extending the end boundary.

1. Overlap Graph & Connected Components (Baseline)

TimeO(n²)
SpaceO(n²)

Model each interval as a graph node with an edge whenever two intervals overlap, then merge every connected component into [minStart, maxEnd].

Time ComplexityO(n²)

Building pairwise overlap edges inspects all n(n - 1) / 2 pairs.

Space ComplexityO(n²)

In the worst case where every interval overlaps, the adjacency list holds O(n²) edges.

How It Works

Merging Without Presorting

If you inspect intervals in raw unsorted order, interval A might bridge two distant intervals B and C. You can group overlapping intervals by building an overlap graph:

  1. Two intervals [a1, a2] and [b1, b2] overlap iff a1 <= b2 && b1 <= a2.
  2. Build an adjacency list of overlapping pairs (O(n²) comparisons).
  3. Traverse each connected component with DFS/BFS, recording [min(start), max(end)].

Sorting by start time eliminates all O(n²) graph construction completely.

Step-by-Step Dry Run

Execution Trace·Step 1 of 2
1Detect Pairwise Overlaps

Compare pairs: [1, 3] overlaps [2, 6]; [8, 10] and [15, 18] remain isolated nodes.

State:edges: [1,3] <-> [2,6]
Strengths
  • +Demonstrates why interval merging is fundamentally connected-component unioning
Trade-offs
  • -O(n²) time and O(n²) adjacency memory fails at n = 10^4

Reference Implementation

Complete implementation for Overlap Graph & Connected Components (Baseline) in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
def merge_intervals_graph(intervals: list[list[int]]) -> list[list[int]]:
n = len(intervals)
adj = {i: [] for i in range(n)}
for i in range(n):
for j in range(i + 1, n):
if intervals[i][0] <= intervals[j][1] and intervals[j][0] <= intervals[i][1]:
adj[i].append(j)
adj[j].append(i)
visited = set()
res = []
for i in range(n):
if i in visited:
continue
stack = [i]
visited.add(i)
min_s, max_e = intervals[i]
while stack:
node = stack.pop()
min_s = min(min_s, intervals[node][0])
max_e = max(max_e, intervals[node][1])
for nei in adj[node]:
if nei not in visited:
visited.add(nei)
stack.append(nei)
res.append([min_s, max_e])
return res

2. Sort by Start Time & Greedy Merge

Optimal
TimeO(n log n)
SpaceO(n)

Sort intervals in ascending order by start time. Iterate through intervals: if the current interval starts before or at the previous end time, merge them by extending the end boundary.

Time ComplexityO(n log n)

Dominated by sorting the N intervals by start time. The subsequent linear merging pass takes O(n). Total runtime is O(n log n).

Space ComplexityO(n)

Consumes space to store the merged output list of intervals (and auxiliary sorting memory).

How It Works

The Invariant: Chronological Start Times

When intervals are unsorted, determining whether two segments collide requires an expensive O(n²) comparison across all pairs.

However, if we sort intervals by their start time (start_i):

  • Any interval that can possibly overlap with interval A must appear directly after A in the sorted list!

The Greedy Merging Rule:

  1. Sort intervals such that intervals[i][0] <= intervals[i + 1][0].
  2. Initialize a merged list res and append the first interval: res.append(intervals[0]).
  3. For each subsequent interval curr in intervals[1..n-1]:
  • Let last be the most recently added interval in res.
  • Case 1: Overlap: If curr.start <= last.end:
  • The intervals collide!
  • Merge them by taking the maximum end boundary: last.end = max(last.end, curr.end)
  • Case 2: No Overlap: If curr.start > last.end:
  • There is a gap between last and curr.
  • curr starts a brand new independent interval!
  • Append curr to res.
  1. Return res.

Step-by-Step Dry Run

Execution Trace·Step 1 of 4
1Sorted Input

[[1, 3], [2, 6], [8, 10], [15, 18]]. Insert [1, 3] into merged list.

State:merged = [[1, 3]]
Strengths
  • +Optimal O(n log n) runtime
  • +Clean single-pass scan after sorting by start time
Trade-offs
  • -Mutates original ordering by requiring a start-time sort

Reference Implementation

Complete implementation for Sort by Start Time & Greedy Merge in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
def merge_intervals(intervals: list[list[int]]) -> list[list[int]]:
if not intervals:
return []
intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]
for current in intervals[1:]:
last = merged[-1]
if current[0] <= last[1]:
last[1] = max(last[1], current[1])
else:
merged.append(current)
return merged
if __name__ == "__main__":
test1 = [[1, 3], [2, 6], [8, 10], [15, 18]]
test2 = [[1, 4], [4, 5]]
print("test1 merged:", merge_intervals(test1))
print("test2 merged:", merge_intervals(test2))
Interactive Visualizer

Trace Array & Matrix mechanics in memory

Step through custom inputs in the Array & Matrix visualizer to inspect pointer updates, array shifts, and call-stack state alongside Merge Intervals.

Open Array & Matrix visualizer

Frequently Asked Questions

Why must we sort by start time before merging?

Sorting by start time orders every left endpoint monotonically, guaranteeing that any interval overlapping the current merged block appears immediately next.

Do touching intervals count as overlapping?

Yes. If [1, 4] and [4, 5] touch at endpoint 4, curr.start <= last.end (4 <= 4) is true and merges them into [1, 5].

Why use `max(last.end, curr.end)` instead of setting `last.end = curr.end`?

Because an earlier interval can completely contain a shorter subsequent one — for example [[1, 10], [2, 5]]. Assigning curr.end directly would shrink [1, 10] to [1, 5].

Edge Cases & Implementation Pitfalls

Boundary Test Cases to Verify

  • Nested containment (e.g., [[1, 10], [2, 3]]) must keep end = 10, not overwrite with 3.
  • Touching boundaries ([[1, 4], [4, 5]]) share point 4 and must merge into [1, 5].
  • Zero-length point intervals ([[2, 2], [2, 3]]) merge via start <= last.end.
  • Single interval input returns unchanged.

Common Bugs to Avoid

  • Setting `last[1] = curr[1]` instead of `Math.max(last[1], curr[1])`, shrinking the merged interval on contained sub-intervals like `[[1, 4], [2, 3]]`.
  • Using strict `<` (`curr[0] < last[1]`) which misses touching intervals like `[1, 4]` and `[4, 5]`.
  • Sorting by end time instead of start time without adjusting merge logic (sorting by end time works for maximum disjoint meetings, NOT interval unions!).

Interview Follow-Up Variations

  • Insert Interval: given an already sorted non-overlapping list plus one new interval, merge in O(n) without re-sorting.
  • Meeting Rooms II: count the minimum number of overlapping conference rooms via a Min-Heap of end times or sweep-line events.

Related Problems

All problems
MediumTwo Pointers

3Sum

Find all unique integer triplets summing to zero. Compare hash-set pair lookup against sorting + two-pointer inward scans with duplicate skipping.

Pattern: Sort then Two Pointers
O(n²) · O(1) to O(n)
Solve
EasyArrays & Hashing

Contains Duplicate

Check whether any integer repeats inside an array. Compare early-exit O(n) Hash Set membership testing against O(1)-space in-place sorting.

Pattern: Hash Set
O(n) · O(n)
Solve
EasyArrays & Hashing

Two Sum

Find indices of two array elements summing to target. Compare O(n²) brute-force scanning against O(n) one-pass complement lookup with a Hash Map.

Pattern: Hash Map
O(n) · O(n)
Solve