HardLinked ListDivide and ConquerHeap (Priority Queue)Merge Sort

1 approach, code in every language

Problem description

You are given an array of k linked lists, where each individual list is already sorted in ascending order by node value.

Merge every list into a single sorted linked list and return the head of that combined list. The result must preserve ascending order across all nodes drawn from every input list.

Some of the input lists may be empty, and the whole array itself may be empty, in which case the merged result is an empty list.

Example 1

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

Output: [1,1,2,3,4,4,5,6]

The three sorted lists are 1->4->5, 1->3->4 and 2->6. Interleaving them in ascending order produces 1->1->2->3->4->4->5->6.

Example 2

Input: lists = []

Output: []

There are no lists to merge, so the result is the empty list.

Constraints

  • k == lists.length
  • 0 <= k <= 10^4
  • 0 <= lists[i].length <= 500
  • -10^4 <= lists[i][j] <= 10^4
  • Each lists[i] is sorted in ascending order
  • The sum of lists[i].length will not exceed 10^4

After the pattern

Now solve one you haven't seen.

Merge Shard Streams is our own problem on the technique behind Merge k Sorted Lists: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free