Skip to content
CodeShare
All problems

Merge K Sorted Lists

Combine any number of sorted linked lists into one.

HardLinked listHeap

You're given an array of k linked lists, lists, each sorted in ascending order. Merge them all into one sorted linked list and return its head.

Lists are written as arrays: [[1, 4], [2]] means two lists, 1 → 4 and 2.

Examples

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
[]
Example 3
Input
lists = [[]]
Output
[]

Constraints

  • 0 <= k <= 10^4
  • Each list has between 0 and 500 nodes.
  • -10^4 <= Node.val <= 10^4