Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Merging overlapping intervals (sort by start, merge when the next interval's start is ≤ the current merged interval's end — touching endpoints count as overlapping) on [1,8], [18,25], [8,10], [4,8], [15,17], [21,24], what is the result?

  1. A. [1,8], [4,8], [8,10], [15,17], [18,25], [21,24]
  2. B. [1,8], [8,10], [15,17], [18,25]
  3. C. [18,25], [15,17], [1,10]
  4. D. [1,10], [15,17], [18,25]

Correct answer: D. [1,10], [15,17], [18,25]

After sorting by start time, two intervals merge whenever the next one's start is ≤ the current merged end (so [2,5] and [5,8] do merge, since they touch at 5); applying this gives [1,10], [15,17], [18,25]. Requiring a strictly smaller start (< instead of ≤) would wrongly keep touching intervals separate, giving [1,8], [8,10], [15,17], [18,25].

More Coding Interview Problems questions

Exams that ask this topic