Problem 432296 · medium · Level 04 Non-Linear Data Structures

Merging k Sorted Sensor Logs

heap · linked list · tuples · k-way merge

Each of k sensors keeps its log of reading times as a linked list, already sorted from earliest to latest. Write merge_k_lists(lists) that combines all the logs into one sorted linked list and returns its head (None when there is nothing to merge).

Folding the logs together two at a time costs O(kN) overall. A heap does better: hold the current front node of every list in a min-heap, pop the smallest, attach it to the result, and push the next node from the same list. Each node passes through the heap once, giving O(N log k).

Examples

Input:  lists = [[2, 6, 9], [1, 6], [3, 4, 10]]
Output: [1, 2, 3, 4, 6, 6, 9, 10]
Input:  lists = []
Output: []
Input:  lists = [[]]
Output: []

Constraints

  • 0 <= k <= 100
  • Each list has at most 500 nodes, sorted ascending; some lists may be empty.

Goals

  • Perform a k-way merge with a heap holding one candidate per list
  • Add a tie-breaker to heap tuples so non-comparable objects are never compared
  • Build a linked list with a dummy head and tail pointer
Starting Python…