Skip to content

Commit fb06b1a

Browse files
committed
Sync LeetCode submission Runtime - 7 ms (91.36%), Memory - 20.2 MB (33.88%)
1 parent 02f4961 commit fb06b1a

File tree

1 file changed

+31
-15
lines changed

1 file changed

+31
-15
lines changed

0023-merge-k-sorted-lists/solution.py

Lines changed: 31 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,40 @@
1-
import heapq
1+
# Approach: Heap
2+
3+
# n = total number of nodes, k = no. of linked lists
4+
# Time: O(n * log k)
5+
# Space: O(k)
26

37
# Definition for singly-linked list.
48
# class ListNode:
59
# def __init__(self, val=0, next=None):
610
# self.val = val
711
# self.next = next
812

13+
import heapq
14+
915
class Solution:
1016
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
11-
q = [(l.val, idx) for idx, l in enumerate(lists) if l]
12-
heapq.heapify(q)
13-
14-
head = curr = ListNode(None)
15-
16-
while q:
17-
val, idx = heapq.heappop(q)
18-
curr.next = ListNode(val)
19-
curr = curr.next
20-
node = lists[idx] = lists[idx].next
21-
if node:
22-
heapq.heappush(q, (node.val, idx))
23-
24-
return head.next
17+
heap = []
18+
19+
# Add the first node from each list to the heap
20+
# We store (value, list_index, node) in heap
21+
for i, lst in enumerate(lists):
22+
if lst:
23+
heapq.heappush(heap, (lst.val, i, lst))
24+
25+
dummy = ListNode(0)
26+
current = dummy
27+
28+
while heap:
29+
val, i, node = heapq.heappop(heap)
30+
31+
# Add the node to our result list
32+
current.next = node
33+
current = current.next
34+
35+
# If there are more nodes in the same list, add the next node to heap
36+
if node.next:
37+
heapq.heappush(heap, (node.next.val, i, node.next))
38+
39+
return dummy.next
40+

0 commit comments

Comments
 (0)