☰ All problems

36. Merge k Sorted Lists

You are given an array lists of k singly linked lists, each sorted in ascending order. Some of the lists may be empty, and lists itself may be empty.

Merge all of them into one sorted linked list and return its head.

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

Explanation: One list, and it has no nodes.

Constraints

  • 0 <= k <= 10^4
  • 0 <= lists[i].length <= 500
  • -10^4 <= Node.val <= 10^4
  • Each list is sorted in ascending order, and the total number of nodes is at most 10^4
💡 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