How would you merge overlapping intervals and validate the result?
Answer
Validate each interval, sort by start, then scan once: extend the current interval when the next start is within its end, otherwise emit it and start a new one. Sorting dominates at O(n log n). Clarify whether touching intervals merge, then test empty input, one interval, nested ranges, equal endpoints, unsorted input and invalid reversed ranges.
Strong answer includes
- sorts before performing a linear merge
- clarifies boundary semantics for touching intervals
- derives tests from the algorithm's invariants
Practical example
Given intervals [1,3], [3,5] and [6,8], a candidate who never clarified whether touching endpoints merge might produce two intervals instead of the interviewer's expected one merged [1,5] plus [6,8], because 3 equals 3 is a boundary case the requirements never explicitly settled.