Skip to the solution
MediumDSA4 min read

How do you merge overlapping intervals?

586 views

The problem

Question presented to candidate: "You are given a list of intervals, each a list [start, end], in no particular order. Write a Python function that merges all overlapping intervals and returns the merged list sorted by start."

What a strong answer should cover:

  • Sort by start, then one pass that either extends the last merged interval or starts a new one.
  • Use max(last_end, end) when extending, because an interval can be nested inside the previous one.
  • Complexity: O(n log n) for the sort plus O(n) for the pass; O(n) for the output.
  • Touching intervals ([1, 4] and [4, 5]): <= merges them; confirm the expected behaviour.
  • Python details: sorted(..., key=lambda iv: iv[0]) returns a new list while list.sort() mutates the caller's list; append a new [start, end] so mutating merged[-1] never changes the input.

Clarifying questions expected:

  • Do touching intervals count as overlapping?
  • May I modify the input list?

Code / implementation expected: Yes โ€” a function merge(intervals) -> list[list[int]] in Python 3.

  • intervals
  • sorting

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

4 min read ยท 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonSort + one pass on seven inputs (touching, nested, unsorted, empty)
PythonThe three classic bugs next to the correct merge

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 82 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you group anagrams together?

Continue