Skip to content

Commit

Permalink
solve: mergeKSortedLists
Browse files Browse the repository at this point in the history
  • Loading branch information
yolophg committed Feb 16, 2025
1 parent 31c9e1e commit 7e67850
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions merge-k-sorted-lists/yolophg.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Time Complexity: O(N log N) - collecting all nodes is O(N), sorting is O(N log N)
# Space Complexity: O(N) - storing all nodes in an array

class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:

arr = []

# collect all nodes from the linked lists
for node in lists:
while node:
arr.append(node)
node = node.next

# sort all nodes based on their value
arr.sort(key=lambda x: x.val)

# reconnect nodes to form the merged linked list
for i in range(len(arr) - 1):
arr[i].next = arr[i + 1]

return arr[0] if arr else None

0 comments on commit 7e67850

Please sign in to comment.