We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 31c9e1e commit 7e67850Copy full SHA for 7e67850
merge-k-sorted-lists/yolophg.py
@@ -0,0 +1,22 @@
1
+# Time Complexity: O(N log N) - collecting all nodes is O(N), sorting is O(N log N)
2
+# Space Complexity: O(N) - storing all nodes in an array
3
+
4
+class Solution:
5
+ def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
6
7
+ arr = []
8
9
+ # collect all nodes from the linked lists
10
+ for node in lists:
11
+ while node:
12
+ arr.append(node)
13
+ node = node.next
14
15
+ # sort all nodes based on their value
16
+ arr.sort(key=lambda x: x.val)
17
18
+ # reconnect nodes to form the merged linked list
19
+ for i in range(len(arr) - 1):
20
+ arr[i].next = arr[i + 1]
21
22
+ return arr[0] if arr else None
0 commit comments