Skip to problem
←

Merge k Sorted Lists

Hard 0 attempts

Given an array lists containing the heads of k singly linked lists, merge them into one list sorted in non-decreasing order and return its head.

Each input list is already sorted and may be empty. Preserve every value, including duplicates across or within lists. If all lists are empty, or lists itself is empty, return null.

You may relink the input nodes. The inner arrays in examples are a display format: your function receives an array of head nodes, not arrays of values.

Function contract

Implement mergeKLists(lists). The editor converts each inner value array into a linked-list head with val and next properties. An empty inner array becomes null; the outer array contains those heads.

Output: Return the head of one non-decreasing linked list containing every input value with its original multiplicity. If there are no nodes, return null (displayed as []).

Example 1

Input
lists = [[1,4,5],[1,3,4],[2,6]]
Output
[1,1,2,3,4,4,5,6]

Example 2

Input
lists = []
Output
[]
Constraints
  • 0 <= k <= 10^4
  • 0 <= lists[i].length <= 500
  • At most 10^4 total nodes; each list is sorted.
  • -10^4 <= node.val <= 10^4

Divide and Conquer

Merge adjacent pairs of lists in rounds. Compare the two current head values, append the smaller node, and advance that list. Once either list ends, attach the remaining suffix. If a round contains an unpaired list, carry it forward unchanged. Repeatedly halve the number of lists until one remains.

Each round visits at most N nodes, and there are at most ceil(log₂ k) rounds. The list-head arrays themselves also require O(k) total processing, which matters when many input lists are empty.

javascript
function mergeKLists(lists) {
  if (!lists.length) return null;
  function merge(a, b) {
    const dummy = { next: null };
    let curr = dummy;
    while (a && b) {
      if (a.val <= b.val) {
        curr.next = a;
        a = a.next;
      } else {
        curr.next = b;
        b = b.next;
      }
      curr = curr.next;
    }
    curr.next = a || b;
    return dummy.next;
  }
  while (lists.length > 1) {
    const merged = [];
    for (let i = 0; i < lists.length; i += 2)
      merged.push(
        i + 1 < lists.length ? merge(lists[i], lists[i + 1]) : lists[i],
      );
    lists = merged;
  }
  return lists[0];
}

Time: O(k + N log(k + 1)), where N is the total node count. Empty input takes O(1).

Space: O(k) auxiliary space for arrays of list heads. Existing nodes are reused.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript