Stack Bash - Master data structures and algorithms

Merge intervals

Medium
Let's say you manage office space, and you want to report the days that it was occupied.
You're given a list of days that workers occupied the space as a list of intervals:
[[0, 3], [2, 5], [9, 10], [4, 6]]
To make the report easy to read, write a function that merges these intervals into the smallest number of disjointed interval.
The above example input should be merged into the following intervals:
[[0, 6], [9, 10]]
Note that the numbers are inclusive. I.e. the intervals [5, 9] and [9, 10] should be merged to [5, 10].
But the intervals [4, 6] and [7, 9] should not be merged as they're considered disjointed.

Try it first

Solution

5 Essential Sorting & Searching Coding Interview Problems

Master Sorting & Searching by trying the coding challenges below.
  1. 1.Merge intervalsMedium
  2. 2.Kth largest in arrayMedium
  3. 3.Intersection of ArraysMedium
  4. 4.Search sorted matrixHard
  5. 5.Search row & col sorted matrixHard

Want to confidently pass your next coding interview?

Stack Bash helps new and veteran software engineers master data structures and algorithms for technical interviews.