Skip to content

Merge Intervals

MediumLeetCode #56Time O(n log n)Space O(n)

You get a list of [start, end] intervals in any order. Merge every group that overlaps and return the resulting intervals. Intervals that only touch at an endpoint count as overlapping.

[[1,3],[2,6],[8,10],[15,18]] -> [[1,6],[8,10],[15,18]]
[[1,4],[4,5]] -> [[1,5]]

The first two overlap (2 is inside [1,3]), so they become [1,6]. The others stand alone. In the second example, 4 is shared, so they merge.

Brute force compares every pair and keeps merging until nothing changes, which is O(n²) or worse. The waste is that unsorted intervals can overlap with anything.

Sort by start. Now an interval can only overlap the group directly before it. Keep a list of merged intervals and look only at its last one. If the new interval starts at or before that one’s end, they overlap: extend the end with max(last_end, new_end). Otherwise nothing later can reach back either, so start a new group.

Show solutionHide solution
def merge(intervals: list[list[int]]) -> list[list[int]]:
merged = []
for start, end in sorted(intervals): # sort by start (on a copy)
if merged and start <= merged[-1][1]: # overlaps or touches the last one
merged[-1][1] = max(merged[-1][1], end) # extend; it may be contained
else:
merged.append([start, end])
return merged
  • Time: O(n log n) — the sort dominates; the sweep after it is one O(n) pass.
  • Space: O(n) — the output list. The sort may use extra space too, depending on the language.
  • Use max for the new end. An interval can sit completely inside the last one ([1,10] then [2,3]). Setting the end to 3 would shrink the group.
  • Use <=, not <. [1,4] and [4,5] share the point 4 and must merge. Ask the interviewer if touching counts.
  • Sort first. The input is not guaranteed to be ordered. Sorting a copy keeps the caller’s list unchanged. The Java version sorts in place, which is fine if you say so.

The list is already sorted and non-overlapping; add one new interval and merge. The trick: no sort needed. Copy everything that ends before the new one starts, absorb everything that overlaps it by widening the new interval, then copy the rest. O(n).

Find the fewest intervals to remove so the rest do not overlap. The trick: greedy. Sort by end and keep an interval whenever it starts at or after the last kept end. Everything skipped is a removal. Ending early leaves the most room.

Interval List Intersections (LeetCode 986)

Section titled “Interval List Intersections (LeetCode 986)”

Two sorted lists of disjoint intervals; return where they overlap. The trick: two pointers. Intersect the current pair as [max(starts), min(ends)] if valid, then advance the pointer whose interval ends first.