☰ All problems

Merge k Sorted Lists

A distributed database spreads one table across k shards. For a query, every shard returns the IDs of its matching rows as a singly linked list sorted in ascending order, and a coordinator has to combine them into one sorted list. A shard with no matches returns an empty list, and the coordinator may receive no lists at all.

Given the array lists of shard results, merge all of their nodes into a single ascending linked list and return its head.

Example 1
Input: lists = [[3,8,12],[1,9],[4,5,20]]
Output: [1,3,4,5,8,9,12,20]
Example 2
Input: lists = [[],[6,6],[]]
Output: [6,6]

Explanation: Empty results contribute nothing, and both copies of the repeated ID are kept.

Example 3
Input: lists = [[-10,0],[-5]]
Output: [-10,-5,0]

Constraints

  • lists holds between 0 and 10^4 linked lists.
  • Each list has at most 500 nodes, and all lists together have at most 10^4 nodes.
  • Node values are integers from -10^4 to 10^4.
  • Every list is sorted in ascending order.
💡 Hint 1

Merging the lists one after another into a growing result works, but the early nodes get rescanned about k times.

💡 Hint 2

The next node of the answer is always the smallest among the current heads of the k lists. Which structure returns the minimum of k items quickly?

💡 Hint 3

Alternatively, merge the lists in pairs, then merge the results in pairs, like the merge step of merge sort.

/**
 * Definition for singly-linked list (provided):
 * function ListNode(val, next) { this.val = val ?? 0; this.next = next ?? null; }
 *
 * @param {ListNode[]} lists
 * @return {ListNode}
 */
function mergeKLists(lists) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc