#56 Merge Intervals
the problem
In plain words
Merge all overlapping intervals and return the non-overlapping intervals that cover exactly the same ranges.
in intervals = [[1,3],[2,6],[8,10],[15,18]]
out [[1,6],[8,10],[15,18]]
in intervals = [[1,4],[4,5]]
out [[1,5]]
Touching intervals count as overlapping here.
in intervals = [[4,7],[1,4]]
out [[1,7]]
The input isn't sorted.
- 1 ≤ intervals.length ≤ 10⁴
- 0 ≤ start ≤ end ≤ 10⁴
your turn
Try it before you peek
Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.
Solve it in the browser
LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.
Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.
Marking the problem solved, or opening every hint, also shows it.
the aha
Key insight
patternInterval merging (sort by start)
After sorting by start, an interval can only overlap the last group you built. Either it stretches that group, or it starts a new one.
solutions
From brute force to optimal
Repeatedly scan all pairs. Merge the first overlapping pair found, then rescan.
- Scan every pair (i, j).
- If they overlap, replace them with their union and restart.
- Stop when a full scan finds nothing; sort the result.
Up to n merges, each found by an O(n²) pair scan.
The working list.
class Solution { public int[][] merge(int[][] intervals) { List<int[]> list = new ArrayList<>(); for (int[] iv : intervals) list.add(new int[] {iv[0], iv[1]}); boolean changed = true; while (changed) { // repeat until no pair overlaps changed = 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]) { // overlap (touching counts) a[0] = Math.min(a[0], b[0]); a[1] = Math.max(a[1], b[1]); list.remove(j); changed = true; break search; } } } } list.sort((x, y) -> Integer.compare(x[0], y[0])); return list.toArray(new int[0][]); }}Sort by start. For each interval: if it starts after the last group ends, open a new group; otherwise stretch the group's end.
- Sort by start.
- If merged is empty or iv[0] > last[1], append a copy.
- Else last[1] = max(last[1], iv[1]).
The sort dominates; the sweep is O(n).
The output list, plus the sort's buffer.
class Solution { public int[][] merge(int[][] intervals) { Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0])); List<int[]> merged = new ArrayList<>(); for (int[] iv : intervals) { int[] last = merged.isEmpty() ? null : merged.get(merged.size() - 1); if (last == null || iv[0] > last[1]) { // gap after the last group? merged.add(new int[] {iv[0], iv[1]}); // start a new group } else { last[1] = Math.max(last[1], iv[1]); // overlap: stretch the group } } return merged.toArray(new int[0][]); }}Dry run
in the room
How to say it in the interview
talk track
- Ask: do touching intervals merge? Is the input sorted? Can I modify it?
- Explain why only the last group matters: everything earlier ends before the last group starts.
- Draw intervals on a number line. The sorted sweep becomes obvious.
traps
last[1] = iv[1]instead ofmaxbreaks on nested intervals like [1,10], [2,3].- Using
>=in the gap check stops [1,4] and [4,5] from merging. - Comparator
(a, b) -> a[0] - b[0]is fine for these constraints, butInteger.compareis the safe habit (subtraction can overflow).
what they ask next
Follow-ups
Intervals arrive as a stream?
Keep them in a TreeMap<start, end>. Use floorKey/ceilingKey to find neighbours and merge them in O(log n) per insert.
Already sorted, and you get one new interval?
That's LC 57 Insert Interval. Do it in O(n) with no sort.
Minimum meeting rooms (LC 253)?
Sort starts and ends separately (or use a min-heap of end times) and count overlaps. See Meeting Rooms II in this chapter.
before you submit
Edge cases to test
- Touching [1,4] and [4,5] → [1,5].
- Nested [1,10] and [2,3] → [1,10]: take the max end.
- Unsorted input like [[4,7],[1,4]] → [[1,7]].
- Single points such as [5,5] are valid intervals.
practise next
Similar problems
- #57Insert IntervalMediumin Intervals
- #759Employee Free TimeHardin IntervalsLeetCode Premium
- #763Partition LabelsMediumin Greedy