Merge Intervals
The problem
Section titled “The problem”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.
Key insight
Section titled “Key insight”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 mergedexport function merge(intervals: number[][]): number[][] { const sorted = [...intervals].sort((a, b) => a[0] - b[0]); // sort by start (on a copy) const merged: number[][] = []; for (const [start, end] of sorted) { const last = merged[merged.length - 1]; if (last && start <= last[1]) { last[1] = Math.max(last[1], end); // overlaps or touches: extend; it may be contained } else { merged.push([start, end]); } } return merged;}import java.util.ArrayList;import java.util.Arrays;import java.util.List;
class Solution { public int[][] merge(int[][] intervals) { Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0])); // sort by start List<int[]> merged = new ArrayList<>(); for (int[] interval : intervals) { if (!merged.isEmpty() && interval[0] <= merged.get(merged.size() - 1)[1]) { int[] last = merged.get(merged.size() - 1); // overlaps or touches: extend last[1] = Math.max(last[1], interval[1]); // it may be contained } else { merged.add(new int[] {interval[0], interval[1]}); } } return merged.toArray(new int[0][]); }}Complexity
Section titled “Complexity”- 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.
Watch out for
Section titled “Watch out for”- Use
maxfor the new end. An interval can sit completely inside the last one ([1,10]then[2,3]). Setting the end to3would 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.
Variations
Section titled “Variations”Insert Interval (LeetCode 57)
Section titled “Insert Interval (LeetCode 57)”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).
Non-overlapping Intervals (LeetCode 435)
Section titled “Non-overlapping Intervals (LeetCode 435)”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.