Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

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 [16,17], [17,23], [17,21], [23,31], [4,6], [6,7], what is the result?

  1. A. [16,31], [4,7]
  2. B. [4,6], [6,7], [16,17], [17,23], [17,21], [23,31]
  3. C. [4,7], [16,31]
  4. D. [4,6], [6,7], [16,17], [17,23], [23,31]

Correct answer: C. [4,7], [16,31]

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

More Coding Interview Problems questions

Exams that ask this topic