Skip to content

Commit 7e67850

Browse files
committed
solve: mergeKSortedLists
1 parent 31c9e1e commit 7e67850

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

merge-k-sorted-lists/yolophg.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)