interviewmind

Merge Intervals

Merge Intervals is a medium coding interview question. You’re given an array intervals, where intervals[i] = [start, end]. Merge every interval that overlaps another, and return the intervals that remain, sorted by start. Below are examples, the constraints and 3 hints; press Practice and Dana, the interviewer, asks it out loud while you answer in TypeScript, Python, Java, C++ or Go.

Updated · By InterviewMind

Practice this question

Free in your browser, no account.

The problem

Coding · Medium

You’re given an array intervals, where intervals[i] = [start, end]. Merge every interval that overlaps another, and return the intervals that remain, sorted by start.

Two intervals overlap when one starts at or before the moment the other ends, so [1, 4] and [4, 5] merge into [1, 5].

Example 1

Inputintervals = [[1,3],[2,6],[8,10],[15,18]]Output[[1,6],[8,10],[15,18]]

[1,3] and [2,6] overlap, so they merge into [1,6].

Example 2

Inputintervals = [[1,4],[4,5]]Output[[1,5]]

Touching ends count as an overlap.

Constraints

  • 1 ≤ intervals.length ≤ 10⁴
  • intervals[i].length = 2
  • 0 ≤ start ≤ end ≤ 10⁴

Hints

Open one at a time, and try the question again after each.

Hint 1

Sort the intervals by start first. After that, any interval that overlaps another sits right next to it in the list.

Hint 2

Walk the sorted list once, keeping a list of merged intervals. Compare each interval only with the last merged one: extend it when they overlap, and start a new one when they don’t.

Hint 3

When you extend, take the larger of the two ends, because one interval can sit entirely inside another, like [1, 10] and [2, 3]. Touching ends, like [1, 4] and [4, 5], still count as an overlap.

Practice it out loud

In the practice room Dana reads the question aloud in your browser’s own voice, with captions, and you answer in the editor beside it, in TypeScript, Python, Java, C++ or Go. It can look like LeetCode, HackerRank, CoderPad or Codility, so the screen is the one you’ll meet. It’s free and needs no account. Run the InterviewMind desktop app beside it and it hears the question the way it hears a real call, so you can see what it would show you in the live round.

Practice this question

More coding questions

interviewmind

Clarity under pressure.

Download for macOSWindows

On an Intel Mac? Download for Intel