InterviewDryRun
Coding interview · Asked at mid and senior level

Merge Intervals

How the interviewer asks it

“Given a list of intervals as start and end pairs, merge every set of overlapping intervals and return the result sorted by start. Intervals that touch, like [1, 4] and [4, 5], merge.”
Sample test input
4
1 3
2 6
8 10
15 18
Expected output
1 6
8 10
15 18

In the practice room your code reads the input from standard input, and Run checks it against tests like this one. Try it now in your browser, in Python or JavaScript.

Typed drills are free and unlimited: the AI scores your answer against the outline below.

What the interviewer is looking for

  • You realise sorting by start is what makes a single pass possible.
  • A precise overlap condition: the next start is less than or equal to the current end.
  • You take the maximum end when merging, so [1, 10] and [2, 3] stays [1, 10].
  • You state O(n log n) time because of the sort, and the space used.

How to structure your answer

  1. 01

    Clarify

    Ask whether the input is sorted, whether touching intervals merge, and whether you may modify the input.

  2. 02

    Sort

    Sort intervals by start.

  3. 03

    Sweep

    Keep the last merged interval. For each next one, if it starts at or before the last end, extend the end to the larger of the two; otherwise push it as a new interval.

  4. 04

    Test

    [[1,3],[2,6],[8,10],[15,18]] gives [[1,6],[8,10],[15,18]]; also try one contained interval and a single interval.

  5. 05

    Complexity

    O(n log n) time for the sort, O(n) for the output.

Best answers from candidates

No candidate answers yet. Type yours, and if it scores 6 or more you can show it here without your name.

Answers are shared by candidates, without names, after a privacy check. Add yours

Common mistakes

  • Setting the end to the next interval's end instead of the maximum of both.
  • Using strict less-than and so leaving touching intervals unmerged.
  • Comparing every pair of intervals, which is O(n²) and easy to get wrong.
  • Forgetting to add the final interval after the loop.

Follow-up questions to expect

  • The intervals arrive as a stream sorted by start and do not fit in memory. What changes?
  • Insert one new interval into an already merged list.
  • Find the minimum number of meeting rooms these intervals need.

Now answer it out loud

Max will ask you this exact question, listen to your answer, push on the weak spots with follow-ups like the ones above, and score you when you finish.

Practice with Max

Free: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.

More coding interview questions

Preparing for this round? Read how to prepare for a coding interview: a four-week DSA plan.