Merge overlapping time intervals
Company: Apple
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates competence in interval and array manipulation, sorting-based algorithm design, overlap detection, and efficient time/space complexity reasoning.
Constraints
- 1 <= intervals.length <= 100000
- Each interval has exactly two integers: [start, end]
- start <= end for every interval
- Interval values fit in 32-bit signed integers
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, so they merge into [1,6]. The other intervals do not overlap.
Input: ([[5,7],[1,4],[4,5],[10,12]],)
Expected Output: [[1,7],[10,12]]
Explanation: After sorting, [1,4], [4,5], and [5,7] all overlap or touch at endpoints, so they merge into [1,7].
Input: ([[42,42]],)
Expected Output: [[42,42]]
Explanation: A single interval is already merged.
Input: ([[-10,-1],[-5,0],[1,3],[3,3],[2,6],[-10,-1]],)
Expected Output: [[-10,0],[1,6]]
Explanation: The negative intervals, including the duplicate [-10,-1], merge into [-10,0]. The intervals [1,3], [3,3], and [2,6] merge into [1,6].
Input: ([[1,10],[2,3],[4,8],[11,12]],)
Expected Output: [[1,10],[11,12]]
Explanation: [2,3] and [4,8] are fully contained inside [1,10], so the merged interval remains [1,10].
Input: ([[-2147483648,-2147483648],[-2147483648,0],[2147483646,2147483647]],)
Expected Output: [[-2147483648,0],[2147483646,2147483647]]
Explanation: The first two intervals overlap at the minimum 32-bit integer boundary and merge into [-2147483648,0].
Hints
- If the intervals are not already sorted, sorting by start time makes it easier to identify overlaps in one pass.
- Keep track of the most recently merged interval and compare each next interval's start with the merged interval's end.