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].
Input: []
Expected Output: []
Explanation: Empty input returns an empty list.
Input: [[1, 4]]
Expected Output: [[1, 4]]
Explanation: A single interval is returned unchanged.
Input: [[1, 10], [2, 3], [4, 5]]
Expected Output: [[1, 10]]
Explanation: Both [2,3] and [4,5] are fully nested inside [1,10], so everything collapses to [1,10].
Input: [[-5, -1], [-3, 0], [2, 4]]
Expected Output: [[-5, 0], [2, 4]]
Explanation: Negative coordinates: [-5,-1] and [-3,0] overlap and merge to [-5,0]; [2,4] is separate.
Input: [[3, 5], [1, 2], [6, 8], [2, 3]]
Expected Output: [[1, 5], [6, 8]]
Explanation: Unsorted input; after sorting, [1,2],[2,3],[3,5] chain-merge into [1,5] via boundary touches and overlap.
Input: [[1, 4], [5, 6]]
Expected Output: [[1, 4], [5, 6]]
Explanation: There is a gap between 4 and 5 (5 > 4), so the intervals stay separate.
Input: [[2, 2], [2, 5]]
Expected Output: [[2, 5]]
Explanation: Zero-length interval [2,2] merges with [2,5] since 2 <= 2.
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.