Merge overlapping intervals
Company: OpenAI
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates algorithmic problem-solving skills focused on interval manipulation, sorting and merging logic, and time/space complexity analysis within the Coding & Algorithms domain, emphasizing practical application.
Constraints
- 0 <= len(intervals) <= 10000
- intervals[i].length == 2
- -10000 <= start <= end <= 10000
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: [[1,4],[4,5]]
Expected Output: [[1,5]]
Explanation: The intervals touch at 4, so they are considered overlapping and merge into [1,5].
Input: []
Expected Output: []
Explanation: An empty input has no intervals to merge.
Input: [[5,7]]
Expected Output: [[5,7]]
Explanation: A single interval is already fully merged.
Input: [[-5,-3],[-4,1],[2,2],[2,3]]
Expected Output: [[-5,1],[2,3]]
Explanation: The first two intervals overlap and merge into [-5,1]. The intervals [2,2] and [2,3] also overlap and merge into [2,3].
Input: [[6,8],[1,9],[2,4],[4,7]]
Expected Output: [[1,9]]
Explanation: After sorting, every interval overlaps with the growing merged range, resulting in one interval [1,9].
Solution
def solution(intervals):
if not intervals:
return []
intervals.sort(key=lambda x: x[0])
merged = [intervals[0][:]]
for start, end in intervals[1:]:
last = merged[-1]
if start <= last[1]:
last[1] = max(last[1], end)
else:
merged.append([start, end])
return mergedTime complexity: O(n log n). Space complexity: O(n).
Hints
- Sorting the intervals by their start value makes it easier to detect overlaps in one pass.
- Keep track of the current merged interval and extend its end when the next interval overlaps.