Algorithm Lab / Exercise

Merge overlapping calendar intervals

Turn a list of time ranges into non-overlapping busy blocks using a sorted scan.

You will learn to

  • Sort intervals by start time
  • Track the current merged end
  • Preserve the original input

Before you start

JavaScript arrays, sorting and loops

Choose a time representation

Represent each busy interval as [start, end] in integer minutes from the start of a day. Assume start is less than end and all inputs are valid. In this exercise touching intervals merge: [60, 90] and [90, 120] form [60, 120]. That is a product decision, so write it down before choosing whether the comparison should use less-than or less-than-or-equal.

Walk a concrete example

Given [[90, 120], [30, 60], [50, 100], [150, 180]], sort by start to obtain [[30, 60], [50, 100], [90, 120], [150, 180]]. Start a result with [30, 60]. Because 50 is at most 60, extend its end to 100. Next, 90 is at most 100, so extend again to 120. Finally, 150 is beyond 120, so append a second block. The result is [[30, 120], [150, 180]].

Avoid shrinking a busy block

For [[10, 100], [20, 30]], the second interval is entirely inside the first. Assigning its end directly would shrink the block to [10, 30]. Instead retain Math.max(currentEnd, nextEnd). Empty input returns an empty list. Copy the pairs before sorting or extending them so the function does not unexpectedly change the caller’s calendar data.

Understand the limits

Sorting costs O(n log n); the scan is O(n). A copied result uses O(n) space in the worst case. Real calendars also need dates, time zones and a policy for overnight events. This activity works only with validated minute ranges within one day. Implement mergeIntervals, inspect the example, and add a nested interval to check that an existing block never shrinks.

Try it yourself

function mergeIntervals(intervals) {
  // Copy, sort, then merge overlapping or touching pairs.
  return [];
}
console.log(mergeIntervals([[90,120],[30,60],[50,100],[150,180]]));

Enable JavaScript for this interactive activity. You can read all lesson explanations above without it.

Continue exploring