Merge Message Context Windows
RedditSoftware Engineer · OnsiteLast updated
This problem tests your ability to merge overlapping intervals efficiently using sorting and greedy techniques, a foundational skill for data reconciliation tasks.
Problem Statement
You are building a message threading feature that tracks "context windows" for ongoing conversations. Each window is represented as a pair of integers [start, end], where start and end are timestamps of messages. Because multiple services log these windows, you often receive redundant or overlapping data.
Given a list of message windows intervals where intervals[i] = [start_i, end_i], merge all overlapping intervals and return an array of the non-overlapping intervals that cover all the windows in the input.
Function Signature
def merge_windows(intervals: List[List[int]]) -> List[List[int]]:
Constraints
1 <= intervals.length <= 10^40 <= start_i <= end_i <= 10^9
Examples
Example 1:
Input: intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]
Output: [[1, 6], [8, 10], [15, 18]]
Explanation: Since [1, 3] and [2, 6] overlap, merge them into [1, 6].
Example 2:
Input: intervals = [[1, 4], [4, 5]]
Output: [[1, 5]]
Explanation: Windows that share a boundary point are considered overlapping and should be merged.
Edge Cases
- Single interval in the list.
- All intervals are disjoint.
- All intervals are nested within one another (e.g.,
[[1, 10], [2, 5], [6, 7]]).
Hints
Hint 1
Consider sorting the list of intervals based on their start timestamps first.
Hint 2
Once sorted, you can iterate through the list and maintain a 'current' merged interval, updating its end time if the next interval overlaps with it.
Hint 3
An overlap occurs if the start of the next interval is less than or equal to the end of the current merged interval.
Follow-up questions
- What is the time and space complexity of your solution, and can you justify why sorting is necessary?
- How would you modify your algorithm if the input intervals were already sorted by their start times?
- If the input was a massive stream of windows that couldn't fit into memory, how would you approach merging them?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.