Skip to main content

Medium sorting · intervals

Busy blocks

Squash an overlapping calendar into the blocks of time you are actually busy.

Write mergeIntervals(intervals): each interval is [start, end] with start <= end. Merge every pair that overlaps or touches, and return the merged intervals sorted by start ascending. [1, 4] and [4, 5] touch, so they become [1, 5]. The input may arrive in any order.

Call show(line) after each interval you place, with the merged list so far as a string like "[1, 6] [8, 10]".

Example: mergeIntervals([[1, 3], [2, 6], [8, 10], [15, 18]]) returns [[1, 6], [8, 10], [15, 18]].

Tests you can see

  • mergeIntervals([[1,3],[2,6],[8,10],[15,18]])[[1,6],[8,10],[15,18]]
  • mergeIntervals([[1,4],[4,5]])[[1,5]]
  • mergeIntervals([[8,10],[1,3],[2,6]])[[1,6],[8,10]]

More tests are hidden. The server runs them all before a time counts.

Call show() while your code works and the run plays back here.

javascriptmergeIntervals()

Tab indents · Cmd/Ctrl+Enter runs