Heap Queue (heapq) in Python | LeetCode Example Last Stone Weight
Heap
Heap data structure is mainly used to represent a priority queue. In Python, it is available using the “heapq
” module. The property of this data structure in Python is that each time the smallest heap element is popped(min-heap).
Whenever elements are pushed or popped, heap structure is maintained.
The heap[0]
element also returns the smallest element each time. Let’s see various Operations on the heap in Python.
Creating a simple heap
The heap.heapify(iterable)
function is used to convert the iterable into a heap data structure. i.e. in heap order.
In this notebook I’ve showed:
- how heapq affects the original
list
- how to
push
andpop
push
andpop
simultaneously withheapq.heappushpop(list, item)
andheapq.heapreplace(list, item)
nlargest(n, list)
andnsmallest(n, list)
Example
|
|
Approach
Turn all int
to negative so that we can properly use Heap
.
pop
the largest 2 and crash them thenpush
them back- till the end
With
heapq
is a binary heap, with $O(log n)$push
and $O(log n)$pop
.1
we know that with our approach we will have $O(nlog n)$ Time Complexity and $O(1)$ Space Complexity.