InterviewPrepKit

Home / Coding / Intervals

Merge Intervals

medium Original β†—
Solving tips
  • Sort by start so every interval that should merge arrives consecutively, then sweep once maintaining a current block; O(n log n) time, O(n) space.
  • Extend the block when start <= last_end, and set the block's end to max(last_end, end) not just end, or a nested interval like [2,3] inside [1,10] wrongly shrinks it.
  • These are closed intervals, so touching intervals like [1,4] and [4,5] must merge: use '<=' in the reach test.
  • Sort by START specifically (not end or descending); the 'only neighbors matter' invariant depends on ascending starts.

Problem

You are given a list of closed intervals [start, end] in no particular order. Whenever two intervals overlap β€” including merely touching at an endpoint, since the intervals are closed β€” they should be fused into a single interval covering both. Return the list of merged intervals: the smallest set of pairwise non-overlapping intervals that covers exactly the same points as the input. Output order should be by start time.

Examples

  • intervals = [[1,3],[2,6],[8,10],[15,18]] β†’ [[1,6],[8,10],[15,18]] β€” [1,3] and [2,6] overlap and fuse into [1,6].
  • intervals = [[1,4],[4,5]] β†’ [[1,5]] β€” closed intervals sharing the point 4 count as overlapping.
  • intervals = [[1,4],[0,2],[3,5]] β†’ [[0,5]] β€” a chain of overlaps collapses into one interval.

Constraints

  • 1 <= len(intervals) <= 10^4
  • 0 <= start <= end <= 10^4

10^4 intervals: repeated pairwise merging (O(n^2)) is the naive path; O(n log n) via sorting is the expected answer.

Think about it first

Hint 1 In the raw input, an interval's merge partners can be anywhere in the list. What preprocessing step guarantees that everything an interval merges with sits right next to it?
Hint 2 After sorting by start, suppose you're building the output left to right and the next interval starts before or at the end of the last interval you've built. What single update handles it? And be careful β€” why is it not just "extend the end"?
Hint 3 Sort by start. Keep the output's last interval as the "current block": if the next interval's start is ≀ the block's end, set the block's end to the max of the two ends (the next interval might be nested inside!); otherwise start a new block.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.