Introduction
A priority queue is one of the elementary data structures used heavily in competitive programming and is one of the favorite topics of interviewers. In this blog, we will code the priority queue using Python.
With one exception, priority queues function in the same manner as normal queues. Each element in the priority queue has a priority associated with it based on which it can be classified into two types :
- Min Priority Queue: Minimum element has the highest priority.
- Max Priority Queue: Maximum element has the highest priority.
Usually, priority queues are used whenever we need to perform operations based on priority. So, with a priority queue, we can easily extract the highest priority element and complete the required operations.
Internally, priority queues are implemented as heaps.
A min priority queue can be implemented using a min-heap, and a max priority queue can be implemented using a max heap. So let us briefly discuss the concepts of heaps, which will help us implement the priority queue.
Also See, Intersection in Python, Swapcase in Python
Heaps
Heap is an almost complete binary tree with the heap property imposed on it.
A binary tree is an almost complete binary tree if its H - 1 level is filled and the last level is filled from left to right without leaving any intermediary node empty. (‘H’ is the height of the binary tree).
Examples of Valid Complete Binary Trees:
Examples of Invalid Complete Binary Trees:
This is an essential property of the heap, which allows us to represent binary trees efficiently using arrays. The root node is kept at index 0, followed by other nodes in a level order fashion.
For Example:
The above complete binary tree can be stored in an array in the following manner:
5 | 3 | 7 | 2 | 4 |
If the parent is at index ‘i’ and indexing is 0 based, the left child can be found at index ‘2 * I + 1’, and the right child can be found at index ‘2 * I + 2’.
If the index of the child is ‘i’, then the parent can be found at index ‘(I - 1) / 2’.
Heap Property:
In a min-heap, every parent’s value is less than all the elements in the left subtree and the right subtree and it is followed recursively down the tree.
In a max heap, every parent’s value is greater than all the elements in the left subtree, and the right subtree and it is followed recursively down the tree.
For example:
In the first binary tree, the root node is maximum, and in the second binary tree, the root node is minimum.
Based on the above concepts, let us now see the implementation of the priority queue using python.