Data Structures & AlgorithmsHardProduct Company SDE · CP practice

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 [8,16], [18,25], [28,35], [21,28], [4,6], what is the result?

  1. A. [4,6], [8,16], [18,35]
  2. B. [4,6], [8,16], [18,28], [28,35]
  3. C. [18,35], [8,16], [4,6]
  4. D. [4,6], [8,16], [18,25], [21,28], [28,35]

Correct answer: A. [4,6], [8,16], [18,35]

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 [4,6], [8,16], [18,35]. Requiring a strictly smaller start (< instead of ≤) would wrongly keep touching intervals separate, giving [4,6], [8,16], [18,28], [28,35].

More Coding Interview Problems questions

Exams that ask this topic