Merge k Sorted Lists

Hard#23merge k lists

You get k linked lists, each sorted in ascending order; some may be empty. Join all their nodes into one sorted linked list and return its head. Our example: 2 → 6, an empty list, 1 → 4 → 7, 3 → 5 — the answer is 1 → 2 → 3 → 4 → 5 → 6 → 7.

input
lists: k linked lists, each sorted in non-decreasing order; any of them may be empty, and so may lists.
returns
The head of one linked list with all their values, sorted in non-decreasing order.
constraints
  • 0 ≤ k ≤ 50
  • 0 ≤ nodes in each list ≤ 100, ≤ 1000 in all
  • −10⁴ ≤ Node.val ≤ 10⁴
  • each list is sorted in non-decreasing order
our 13 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode[]} lists
 * @return {ListNode}
 */
function mergeKLists(lists) {

}
Ctrl ↵
format
reset

saved in this browser

13 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more heap and top k problems

Pattern “Heap and top K” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.