Merge K timestamped lists with timestamp coalescing
Company: Citadel
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates algorithmic skills in merging multiple sorted sequences, coalescing records by key (timestamp), merging sorted value arrays, and analyzing time and space complexity.
Constraints
- 0 <= k <= 10^4
- Let N be the total number of records across all lists; N <= 10^5
- Let M be the total number of integers across all values arrays; M <= 10^5
- Each input list is sorted by timestamp in non-decreasing order
- Each values array is sorted in non-decreasing order
- Timestamps fit in 32-bit signed integer
Examples
Input: ([[(1, [1, 4]), (3, [2])], [(1, [0, 5]), (2, [7])], [(3, [3, 3])]],)
Expected Output: [(1, [0, 1, 4, 5]), (2, [7]), (3, [2, 3, 3])]
Explanation: Timestamp 1 combines records from the first and second lists. Timestamp 3 combines records from the first and third lists.
Input: ([],)
Expected Output: []
Explanation: There are no input lists, so the merged result is empty.
Input: ([[(-2, [-5, 0]), (1, [2]), (1, [3, 3])], [(-2, [-4]), (0, []), (1, [1, 4])], [(-1, [7])]],)
Expected Output: [(-2, [-5, -4, 0]), (-1, [7]), (0, []), (1, [1, 2, 3, 3, 4])]
Explanation: This checks negative timestamps, an empty values array, and repeated timestamp 1 within the same list.
Input: ([[(5, [1, 1])], [], [(5, [0, 2]), (6, [3])], [(5, [])]],)
Expected Output: [(5, [0, 1, 1, 2]), (6, [3])]
Explanation: All records with timestamp 5 are coalesced, including one with an empty values array. Timestamp 6 remains separate.
Hints
- Use a min-heap to keep track of the next smallest timestamp among the current heads of the k lists.
- When you find the smallest timestamp t, keep removing heap entries with timestamp t and merge all of their sorted values arrays into one sorted array.