Priority Queue Set 1: Introduction
### Introduction to Priority Queue
A Priority Queue is an abstract data structure that is used to store and manage a collection of elements with each element being associated with a priority. It supports the following operations:
1. Insertion: Inserts an element in the priority queue with an associated priority.
2. Deletion: Deletes the element with the highest priority in the priority queue.
3. Extract-Max/Extract-Min: Returns the element with the highest/lowest priority in the priority queue.
Priority Queues are used in various applications such as task scheduling, graph algorithms, and data compression. In task scheduling, the element with the highest priority is given the highest priority to be executed first. In graph algorithms, the element with the highest priority is used to traverse the graph. In data compression, the element with the highest priority is used to compress the data more effectively.
Priority queues are implemented using various data structures such as an array, linked list, binary heap, etc. Depending on the data structure used, the time complexity of the operations can vary. For example, the time complexity of insertion and deletion operations using an array is O(1).
Worried About Failing Tech Interviews?
Attend our webinar on
"How to nail your next tech interview" and learn
Founder, Interview Kickstart
Our tried & tested strategy for cracking interviews
How FAANG hiring process works
The 4 areas you must prepare for
Register for Webinar
How you can accelerate your learnings
A Priority Queue is a data structure used to store and manage data elements in an ordered sequence according to their priority. It is similar to a regular queue, but instead of being organized in a FIFO (First-in, First-out) manner, it is organized so that the element with the highest priority is always at the front of the queue.
Essentially, a priority queue is a collection of data elements such that each element has a priority associated with it. When an element is added to the Priority Queue, it is inserted in the correct position based on its priority. Higher priority elements are placed in the front of the queue, while lower priority elements are placed in the back.
Below is a sample code for a Priority Queue in Python:
self.queue = 
return ' '.join([str(i) for i in self.queue])
return self.queue == 
def insert(self, data):
max = 0
for i in range(len(self.queue)):
if self.queue[i] > self.queue[max]:
max = i
item = self.queue[max]
q = PriorityQueue()
while not q.isEmpty():
# Output: 14 12 7 1