Merge overlapping intervals
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: Merge overlapping intervals evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Constraints
- 0 <= number of intervals <= 10^5
- Each interval is [start, end) with start <= end
- -10^9 <= start <= end <= 10^9
- Intervals may be given in any order (unsorted)
- Half-open semantics: intervals touching exactly at a boundary (next.start == current.end) are merged
Examples
Input: [[1, 3], [2, 6], [8, 10], [15, 18]]
Expected Output: [[1, 6], [8, 10], [15, 18]]
Explanation: [1,3] and [2,6] overlap (2 < 3) and merge into [1,6]; the others are disjoint.
Input: [[1, 4], [4, 5]]
Expected Output: [[1, 5]]
Explanation: Half-open intervals touching at boundary 4 (next.start == current.end) are contiguous and merge into [1,5].
Hints
- Sort the intervals by their start coordinate first — this guarantees any interval that overlaps the current merged block starts at or after the current block's start.
- Walk through the sorted list maintaining a single 'current' merged interval. For each next interval, if next.start <= current.end the two overlap or touch, so extend current.end = max(current.end, next.end).
- If next.start > current.end there is a gap, so finalize the current interval and begin a new one. Handle the empty-input case up front by returning an empty list.