LC 23 - Merge k Sorted Lists
LC 23 - Merge k Sorted Lists
Question
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
Example 1:
1
2
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output:`[1,1,2,3,4,4,5,6]
Explanation: The linked-lists are: [ 1->4->5, 1->3->4, 2->6 ] merging them into one sorted linked list: 1->1->2->3->4->4->5->6
Example 2:
1
2
Input: lists = []
Output: []
Example 3:
1
2
Input: lists = [[]]
Output: []
Constraints:
k == lists.length0 <= k <= 1040 <= lists[i].length <= 500-104 <= lists[i][j] <= 104lists[i]is sorted in ascending order.- The sum of
lists[i].lengthwill not exceed104.
Links
Question here and solution here
Solution
concept
This question is an extension to [[21. Merge Two Sorted Lists]], we basically iterate through the list of linked list and merge each pair using the solution from the previous questions to merge two list together
code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
if not lists or len(lists) == 0:
return None
while len(lists) > 1:
_merged_list = [] # tmp variable
for i in range(0, len(lists), 2):
l1 = lists[i]
l2 = lists[i + 1] if i + 1 < len(lists) else None
_merged_list.append(self.merge_lists(l1, l2))
lists = _merged_list
return lists[0]
def merge_lists(self, l1, l2):
"""
solution of 21. Merge Two Sorted Lists
"""
dummy = ListNode()
tail = dummy
while l1 and l2:
if l1.val < l2.val:
tail.next = l1
l1 = l1.next
else:
tail.next = l2
l2 = l2.next
tail = tail.next
if l1:
tail.next = l1
elif l2:
tail.next = l2
return dummy.next
Complexity
time: $O(n*k)$, k is the total number of lists and n is the total number of nodes across k lists.
space: $O(1)$
This post is licensed under CC BY 4.0 by the author.