Merge Intervals

MediumIntervals · Sorting🧩 Intervals & Line SweepLeetCode #56 ↗Updated

Problem

You get a list of closed intervals [start, end] in arbitrary order. Combine every group of intervals that overlap (touching endpoints count, e.g. [1,4] and [4,5]) and return the resulting non-overlapping intervals that cover exactly the same points.
Input[[1,3],[2,6],[8,10],[15,18]]Output[[1,6],[8,10],[15,18]]
Input[[1,4],[4,5]]Output[[1,5]]

1 ≤ n ≤ 104  ·  0 ≤ start ≤ end ≤ 104

Try it yourself

Java
class Solution {
    public int[][] merge(int[][] intervals) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
After sorting by start, any interval that overlaps the merged block must overlap its last interval — so one left-to-right pass comparing with the last merged end is enough.
PatternIntervals & Line Sweep

Instinct See [start, end] pairs, meetings, bookings or the word "overlap"? Sort by an endpoint, then sweep left to right carrying one running fact.

Memory hack Sort, then sweep - start time to merge, end time to choose, +1/-1 events to count the crowd.

Open the Intervals & Line Sweep guide →

Approaches

Brute ForceRepeated Pairwise Merging

Time O(n³)Space O(n)

Search all pairs for two overlapping intervals (a.start ≤ b.end and b.start ≤ a.end), replace them by their union, and restart. Each merge removes one interval and a full pair search costs O(n²); when no pair overlaps, we are done.

Java
public int[][] merge(int[][] intervals) {
    List<int[]> list = new ArrayList<>();
    for (int[] in : intervals) list.add(in.clone());
    boolean merged = true;
    while (merged) {
        merged = false;
        search:
        for (int i = 0; i < list.size(); i++) {
            for (int j = i + 1; j < list.size(); j++) {
                int[] a = list.get(i), b = list.get(j);
                if (a[0] <= b[1] && b[0] <= a[1]) {
                    a[0] = Math.min(a[0], b[0]);
                    a[1] = Math.max(a[1], b[1]);
                    list.remove(j);
                    merged = true;
                    break search;
                }
            }
        }
    }
    return list.toArray(new int[0][]);
}

Obviously correct, but cubic — hopeless for 104 intervals.

At a glance

LevelApproachTimeSpace
Brute ForceRepeated Pairwise MergingO(n³)O(n)
BetterInsert One by One into a Disjoint SetO(n²)O(n)
OptimalSort by Start + Single SweepO(n log n)O(n)
Common pitfalls
  • Overwriting the end with in[1] instead of max — breaks on nested intervals like [1,10],[2,3].
  • Using < vs ≤ wrongly — touching intervals [1,4],[4,5] must merge.
  • Forgetting to sort first — the sweep only works on start-ordered input.
Interview tips
  • Clarify whether touching endpoints count as overlap.
  • Draw intervals on a number line — makes the sorted sweep obvious.
  • Mention that sorting in place mutates the caller's input; copy if that matters.
Pattern
Sort by start + sweep → merging, covering or counting overlaps among intervals.
My notes saved in this browser