InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Intervals

Merge Intervals

medium Original ↗ 00:00

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 why is it not simply "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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug