-2

I'm working on Merge K Sorted Linked Lists from Leetcode and the optimal solution requires use of a heap. When unpacking the tuple from heapq.heappop(), I figured I would use _, _, node to unpack, as I'm not using the value or index anywhere else in the code. However this throws the following TypeError:

enter image description here

I understand that this error is the result of the heap trying to compare the ListNode object instead of the values and index, but this should not be the case as I've clearly defined it to compare the first 2 objects before the last. When unpacking with val, i, node = heapq.heappop(heap) the code runs fine.

import heapq
# 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]:
        heap = []

        dummy = ListNode()
        curr = dummy

        for i, node in enumerate(lists):
            if node:
                heapq.heappush(heap, (node.val, i, node)) #Add to the heap. Compare by value, then index

        while heap:
            val, i, node = heapq.heappop(heap) #Working line
            #_, _, node = heapq.heappop(heap) #Non-working line
            curr.next = node
            curr = node
            node = node.next
            if node: #If we're not at the end of the list, add to the heap
                heapq.heappush(heap, (node.val, i, node))
        
        return dummy.next
1
  • 4
    I guess one problem with your code is: In your second-to-last line, you call again heapq.heappush(heap, (node.val, i, node)). If you use _, _, node = heapq.heappop(heap) then the i value from your for-loop is used (since i does not get a new value in the while loop). If you use val, i, node = heapq.heappop(heap), then i gets a new value. I am not sure if this is the actual cause of the error though.
    – simon
    Commented 5 hours ago

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.