Priority Queue
Priority Queue
One important variation of a queue is called a priority queue. A priority queue acts like a queue in that you dequeue an item by removing it from the front. However, in a priority queue the logical order of items inside a queue is determined by their priority. The highest priority items are at the front of the queue and the lowest priority items are at the back. Thus when you enqueue an item on a priority queue, the new item may move all the way to the front.
You can probably think of a couple of easy ways to implement a priority queue using sorting functions and lists. However, inserting into a list is 𝑂(𝑛) and sorting a list is 𝑂(𝑛log𝑛). We can do better. The classic way to implement a priority queue is using a data structure called a binary heap. A binary heap will allow us both enqueue and dequeue items in 𝑂(log𝑛).
The binary heap is interesting to study because when we diagram the heap it looks a lot like a tree, but when we implement it we use only a single list as an internal representation. The binary heap has two common variations: the min heap, in which the smallest key is always at the front, and the max heap, in which the largest key value is always at the front. In this section we will implement the min heap. We leave a max heap implementation as an exercise.
Priority Queue in Python
Priority Queue is an extension of the queue with following properties. 1) An element with high priority is dequeued before an element with low priority. 2) If two elements have the same priority, they are served according to their order in the queue.
Below is simple implementation of priority queue.
Output:
Note that the time complexity of delete is O(n)
in above code.
heapq
- Heap queue algorithm
heapq
- Heap queue algorithmheapq.heappush
(heap, item)Push the value item onto the heap, maintaining the heap invariant.
heapq.heappop
(heap)heapq.heapify
(x)Transform list x into a heap, in-place, in linear time.
LintCode 4.Ugly Number II
References
Last updated