pythonheapq

Heapop and Heappush with a regular list (non-heapified list)


So I've seen various posts where users get "unusual/unexpected" results when trying to heappop from a regular list. (ex: Unusual result from heappop?) The solution of course is to heapify it first.

However, for this LeetCode solution heapq methods are used on a regular list that isn't heapified prior to using the methods yet still return the correct expected results. Is this because when you use heappop/heappush onto a regular list it just pops/adds the first element in the list?


Solution

  • In the example they are using heappop on a list that initially contains a single element (the source), so it satisfies the heap property.
    It is not mandatory to use heapify on a list before using functions such as heappop or heappush. Indeed the list might be empty, contain a single element, or be a list that already satisfies the heap property.

    Example:

    >>> l = [1, 3, 2, 5, 4] # initial list that respects the heap property
    >>> heappop(l)
    1
    >>> heappop(l)
    2
    >>> heappop(l)
    3
    >>> heappop(l)
    4
    >>> heappop(l)
    5