You are given an array of k linked lists. Each list is sorted in ascending order. Merge all of them into one sorted linked list and return its head.
Function Signature
def merge_k_lists(lists: list[Optional[ListNode]]) -> Optional[ListNode]:
Rules
-
A
ListNode
has two fields:
val
, an integer, and
next
, the following node or
None
.
-
In the examples each linked list is written as the list of its values from head to tail, so
[2, 5, 7]
means
2 -> 5 -> 7
. An empty list
[]
stands for a
None
head.
-
The returned list is written the same way. It must be sorted in ascending order and keep every node, including duplicate values.
Constraints
-
k == len(lists)
-
0 <= k <= 10^4
-
-10^4 <= Node.val <= 10^4
-
Each list is sorted in ascending order.
Examples
Input: lists = [[2, 5, 7], [3, 6, 8], [4, 9]]
Output: [2, 3, 4, 5, 6, 7, 8, 9]
The lists 2 -> 5 -> 7, 3 -> 6 -> 8 and 4 -> 9 hold eight values in total, and the output lists all eight in ascending order.
Input: lists = []
Output: []
With no lists there are no nodes, so the function returns None.
Input: lists = [[]]
Output: []
One list is present but it is empty, so the result is still None.