Merge Overlapping Intervals with a Sweep
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Take-home Project
Quick Answer: Implement `merge_intervals(intervals)` for closed integer intervals `[start, end]` with `start <= end`. Work through the function contract, boundary cases, correctness argument, and time and space complexity expected in a production-quality solution.
Constraints
- 0 <= len(intervals) <= 200000; each interval has exactly two integers start <= end.
- Every endpoint is from -10^9 through 10^9.
- Intervals are closed, so a shared endpoint belongs to both and must merge; the input must not be mutated.
Examples
Input: ([],)
Expected Output: []
Explanation: An empty input has an empty union.
Input: ([[2, 2]],)
Expected Output: [[2, 2]]
Explanation: A singleton point interval remains unchanged.
Hints
- Test empty and singleton inputs, duplicates, nested intervals, and disjoint intervals.
- Include two closed intervals sharing exactly one endpoint.
- Use unordered intervals spanning negative and positive endpoint values, then verify canonical output order.