Priority Queue in Data Structure: Characteristics, Types & Implementation
By Rohit Sharma
Updated on Dec 06, 2025 | 16 min read | 61.81K+ views
Share:
Working professionals
Fresh graduates
More
By Rohit Sharma
Updated on Dec 06, 2025 | 16 min read | 61.81K+ views
Share:
Table of Contents
The Priority Queue in Data Structure is a critical abstract data type that dictates element processing by priority, not insertion order (FIFO). This dynamic organization ensures the most critical element is always handled first, a principle vital for efficient systems.
A classic priority queue example is found in navigation and pathfinding, such as in Google Maps, where a min-priority queue quickly finds the shortest route. Conversely, systems like operating system schedulers use a max-priority queue to manage urgent tasks. These contrasting types of priority queue demonstrate its versatility.
This article provides a comprehensive look at the core mechanics, practical applications, and step-by-step implementation of the priority queue, offering key insights for algorithm and system optimization.
Explore data science online courses from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.
Popular Data Science Programs
A priority queue in data structure is an abstract data type (ADT) that organizes elements based on their priority rather than the order in which they were added. Unlike a regular queue, which follows a first-in-first-out (FIFO) order, a priority queue processes the element with the highest priority first. This makes it a versatile tool for handling scenarios where priority matters more than sequence.
Let’s consider priority queue in data structure example using a min-priority queue, where elements are arranged in ascending order:
Check out: Free Python Course with Certification
Unlike a standard queue, where elements are processed in the order they arrive, a priority queue in data structure ensures that high-priority items are handled first. Here are its core characteristics:
Know the Difference Between Data Types and Data Structures!
Here is a priority queue in data structure example, in a hospital’s emergency room, a patient with a critical condition would be treated first (highest priority). If two patients have similar conditions, the one who arrived is attended to first.
Priority queues are essential in scenarios requiring efficient and organized task processing, ensuring that the most critical items are addressed without delays.
Data Science Courses to upskill
Explore Data Science Courses for Career Progression
A priority queue organizes elements based on their assigned priority, and the type of priority queue determines how these priorities are interpreted. There are two primary types of priority queues: ascending order priority queues and descending order priority queues. These structures differ in how they assign priority and process elements. Let’s explore them in detail.
In an ascending order priority queue in data structure, elements with lower values are considered higher priority. This means that when dequeuing, the smallest value is removed first. The priority is inversely proportional to the numerical value of the elements.
Consider a priority queue with elements: 2, 4, 6, 8, 10.
In a descending order priority queue, elements with higher values are given precedence. This means that the largest value is dequeued first. The priority is directly proportional to the numerical value of the elements.
Consider a priority queue example with elements: 1, 2, 3, 4, 5, 9.
Feature |
Ascending Order Priority Queue |
Descending Order Priority Queue |
Priority Rule |
Lower value = Higher priority |
Higher value = Higher priority |
First Element Dequeued |
Smallest value |
Largest value |
Common Implementation |
Min-heap |
Max-heap |
Primary Use Case |
Pathfinding, cost-efficient operations |
Task scheduling, urgent tasks management |
Priority queue in data structure can be implemented using various data structures. Each method offers distinct advantages and trade-offs, depending on the use case.
A linked list can implement a priority queue in data structure by maintaining elements in an order based on their priority. New elements are inserted at the correct position to preserve the order.
Implement a priority queue in data structure using a linked list where elements are inserted based on their priority, and the highest-priority element can be dequeued efficiently.
cpp
#include <bits/stdc++.h>
using namespace std;
// Node structure for the priority queue
struct Node {
int data;
int priority;
Node* next;
};
// Function to create a new node
Node* newNode(int d, int p) {
Node* temp = new Node();
temp->data = d;
temp->priority = p;
temp->next = nullptr;
return temp;
}
// Function to remove the element with the highest priority
void pop(Node** head) {
Node* temp = *head;
*head = (*head)->next;
delete temp;
}
// Function to add an element into the priority queue
void push(Node** head, int d, int p) {
Node* temp = newNode(d, p);
// If the queue is empty or new node has higher priority than the head
if (*head == nullptr || (*head)->priority < p) {
temp->next = *head;
*head = temp;
} else {
Node* start = *head;
while (start->next != nullptr && start->next->priority >= p) {
start = start->next;
}
temp->next = start->next;
start->next = temp;
}
}
// Function to get the element with the highest priority
int peek(Node* head) {
return head->data;
}
// Driver code
int main() {
Node* pq = nullptr;
push(&pq, 10, 2);
push(&pq, 20, 4);
push(&pq, 30, 3);
push(&pq, 40, 1);
while (pq != nullptr) {
cout << "Top element: " << peek(pq) << endl;
pop(&pq);
}
return 0;
}
Output:
Top element: 20
Top element: 30
Top element: 10
Top element: 40
A binary heap is the most efficient way to implement a priority queue in data structure. It uses a complete binary tree structure, ensuring logarithmic time for insertion and deletion operations.
Implement a priority queue in data structure using a binary heap, allowing efficient insertion and removal of the highest-priority element.
cpp
#include <bits/stdc++.h>
using namespace std;
// Class for a max-heap-based priority queue
class PriorityQueue {
vector<int> heap;
// Heapify-down to maintain the heap property after deletion
void heapifyDown(int idx) {
int largest = idx;
int left = 2 * idx + 1;
int right = 2 * idx + 2;
if (left < heap.size() && heap[left] > heap[largest]) largest = left;
if (right < heap.size() && heap[right] > heap[largest]) largest = right;
if (largest != idx) {
swap(heap[idx], heap[largest]);
heapifyDown(largest);
}
}
// Heapify-up to maintain the heap property after insertion
void heapifyUp(int idx) {
if (idx == 0) return;
int parent = (idx - 1) / 2;
if (heap[idx] > heap[parent]) {
swap(heap[idx], heap[parent]);
heapifyUp(parent);
}
}
public:
// Insert a new element
void push(int val) {
heap.push_back(val);
heapifyUp(heap.size() - 1);
}
// Remove the element with the highest priority
void pop() {
if (heap.empty()) return;
heap[0] = heap.back();
heap.pop_back();
heapifyDown(0);
}
// Get the element with the highest priority
int peek() {
return heap.empty() ? -1 : heap[0];
}
// Check if the queue is empty
bool isEmpty() {
return heap.empty();
}
};
// Driver code
int main() {
PriorityQueue pq;
pq.push(10);
pq.push(50);
pq.push(30);
pq.push(20);
while (!pq.isEmpty()) {
cout << "Top element: " << pq.peek() << endl;
pq.pop();
}
return 0;
}
Top element: 50
Top element: 30
Top element: 20
Top element: 10
Priority queues in data structure can also be implemented using arrays, either ordered or unordered.
Implement a priority queue using an array, where elements are stored with their priority values, and the highest-priority element is retrieved efficiently.
cpp
#include <bits/stdc++.h>
using namespace std;
// Priority queue using unordered array
class PriorityQueue {
vector<pair<int, int>> arr;
public:
// Add an element with priority
void push(int val, int priority) {
arr.push_back({priority, val});
}
// Remove the element with the highest priority
void pop() {
auto it = max_element(arr.begin(), arr.end());
arr.erase(it);
}
// Get the element with the highest priority
int peek() {
auto it = max_element(arr.begin(), arr.end());
return it->second;
}
// Check if the queue is empty
bool isEmpty() {
return arr.empty();
}
};
// Driver code
int main() {
PriorityQueue pq;
pq.push(10, 2);
pq.push(20, 5);
pq.push(15, 3);
while (!pq.isEmpty()) {
cout << "Top element: " << pq.peek() << endl;
pq.pop();
}
return 0;
}
Top element: 20
Top element: 15
Top element: 10
A binary search tree (e.g., AVL or Red-Black Tree) can implement a priority queue in data structure by maintaining priority ordering in its structure.
Operation |
Unordered Array |
Ordered Array |
Binary Heap |
BST |
Insert |
O(1) |
O(n) |
O(logn) |
O(logn) |
Peek |
O(n) |
O(1) |
O(1) |
O(1) |
Delete |
O(n) |
O(1) |
O(logn) |
O(logn) |
Priority queues in data structure are widely used in various systems and algorithms where prioritizing tasks or data is essential. Here are some common applications explained with practical priority queue examples to show their importance.
Operating systems use priority queues to manage and schedule tasks based on their priority level.
Priority Queue Example:
In a computer system, processes are given priority levels. For instance:
The CPU executes Task A first, followed by Task B and Task C. This ensures urgent tasks, such as system updates, are completed before less critical ones. Priority queues make this scheduling efficient and organized.
In this algorithm, a min-priority queue in data structure stores nodes based on their current shortest distance from the source. The node with the smallest distance is processed first.
Example of Priority Queue:
In a navigation system, such as Google Maps, the shortest route is calculated using Dijkstra’s algorithm. A priority queue helps prioritize the next closest node to evaluate, ensuring the most efficient path is found.
This algorithm uses a min-priority queue to select edges with the smallest weights to construct a minimum spanning tree.
Priority Queue Example:
In a network design, such as laying fiber-optic cables, Prim’s algorithm helps minimize costs by selecting the shortest connections between points.
Priority queues are used in Huffman coding, a popular method for reducing file sizes.
How It Works:
Huffman coding assigns shorter binary codes to frequently occurring characters and longer codes to less frequent ones. A min-priority queue combines the characters with the lowest frequencies first.
Example of Priority Queue:
If a text contains the following character frequencies:
The priority queue helps build a binary tree where characters with the smallest frequencies (C and D) are combined first. This tree generates efficient encodings, reducing the overall size of the compressed file.
Priority queues are used in simulations to handle events based on their priority, ensuring critical tasks are processed before others.
Example of Priority Queue:
In a hospital’s emergency room, patients are assigned priorities based on the severity of their condition:
A priority queue ensures Patient X is attended to first, followed by Patient Z and Patient Y.
Other Simulation Scenarios:
Routers use priority queues to manage data packets. Critical packets, like live video streams or emergency signals, are prioritized over less important packets like file downloads.
Priority Queue Example:
If a router processes the following packets:
The priority queue ensures live stream data is transmitted first, maintaining smooth performance for time-sensitive tasks.
Priority queues are used in A* search to explore paths based on their cost and estimated distance to the target.
Priority Queue Example:
In robotic navigation, the algorithm uses a priority queue to evaluate the most promising paths first, reducing time and computation required to reach the destination.
Subscribe to upGrad's Newsletter
Join thousands of learners who receive useful tips
Priority queues are a game-changer in data structures, powering solutions in navigation, scheduling, and more. Learning them sharpens your problem-solving skills and helps you tackle advanced algorithms like Dijkstra’s shortest path and Huffman coding.
Ready to strengthen your skills? upGrad’s expert-led courses in data structures and algorithms are the perfect way to grow.
Your next career move starts here! Explore upGrad Courses Now!
Accelerate your career with Data Science courses from top universities. Join today to earn Executive PG, Advanced Certificates, or Master’s Programs!
In conclusion, a Priority Queue is a specialized data structure that efficiently manages elements based on priority rather than insertion order. It is widely used in scenarios such as scheduling algorithms, Dijkstra's shortest path algorithm, and in tasks that require real-time processing of high-priority events.
The time complexity of a Priority Queue can vary depending on the implementation, with common operations like insertion and deletion having complexities of O(log n) in binary heaps. Understanding how to effectively implement and utilize a Priority Queue is crucial for optimizing performance in systems that require prioritized task handling, making it an essential tool for developers and computer scientists.
Ready to master Priority Queues? upGrad offers expert-led courses on data structures, with personalized career counseling to help you advance in your coding journey. Unlock your potential and take the next step in your data structure career today with upGrad!
Unlock the power of data with our popular Data Science courses, designed to make you proficient in analytics, machine learning, and big data!
Elevate your career by learning essential Data Science skills such as statistical modeling, big data processing, predictive analytics, and SQL!
Stay informed and inspired with our popular Data Science articles, offering expert insights, trends, and practical tips for aspiring data professionals!
The Binary Heap (either a Min-Heap or Max-Heap) is the most efficient data structure for implementing a priority queue due to its fast time complexity. It ensures that both insertion and deletion operations take only $O(\log n)$ time. While other data structures like sorted or unordered arrays and linked lists can be used, they lead to much slower $O(n)$ worst-case complexity for one of the primary operations, making the heap the preferred choice for real-world data structure applications.
A primary example of priority queue usage is in a hospital's Emergency Room (ER) or in CPU Scheduling within an operating system. In the ER, patients aren't treated first-come, first-served; instead, those with the highest medical priority (most critical condition) are attended to first. This ensures efficient, urgency-based task processing, which is crucial for managing critical resources and tasks in both medical and computer science applications, optimizing system performance.
The two fundamental types of priority queue are the Min-Priority Queue and the Max-Priority Queue. A Min-PQ ensures that the element with the smallest value has the highest priority and is dequeued first—this is common in algorithms like Dijkstra's. Conversely, a Max-PQ ensures the element with the largest value has the highest priority, which is often used in event simulation and sorting. These types allow flexible organization of data based on priority rules.
In Dijkstra’s algorithm, a min-priority queue stores and manages the nodes (vertices) of a graph based on their shortest calculated distance from the starting node. The priority queue ensures that the node with the currently smallest distance is always processed next. This efficient selection mechanism is vital for shortest path calculations, significantly improving the algorithm's performance and making it essential for navigation systems and network routing optimization.
For a priority queue implemented using a binary heap, the time complexity for core operations is highly efficient. Accessing the highest-priority element (Peek) is $O(1)$. Both inserting a new element (insertion) and removing the highest-priority element (Deletion) take $O(\log n)$ time, where $n$ is the number of elements. This logarithmic complexity is why the heap is the industry-standard data structure for scalable and fast priority management.
Yes, a priority queue can easily handle elements that share the same priority value. When this occurs, the queue typically adheres to the First-In, First-Out (FIFO) rule for those specific elements. This means that among all items with the highest identical priority, the one that was inserted earliest into the queue is the one that will be removed or processed first, maintaining fairness in the data structure.
The primary operations performed on a priority queue are: insert() (or push) to add an element with its priority, extractMax() or extractMin() (or poll) to remove and return the element with the highest priority, and peek() (or top) to view the highest priority element without removing it. These operations allow for dynamic management and retrieval of data based on importance.
A Min-Priority Queue prioritizes elements with the smallest value, meaning the minimum element is considered the "highest" priority (e.g., shortest distance). A Max-Priority Queue prioritizes elements with the largest value, meaning the maximum element is considered the "highest" priority (e.g., largest task size). The choice depends entirely on whether the smallest or largest value represents the task's urgency.
A heap implementation is more efficient than a sorted array because insertion into a sorted array requires shifting elements to maintain order, resulting in $O(n)$ time. In contrast, insertion into a heap only involves a 'heapify-up' operation, which is $O(\log n)$. While deletion is fast in both, the $O(\log n)$ insertion time in a heap makes it superior for frequent dynamic updates common in algorithms.
Yes, a priority queue is the core component of the Heap Sort algorithm. By inserting all elements into a Max-Priority Queue and then repeatedly extracting the maximum element one by one, the elements are retrieved in descending order, thus sorting the data efficiently. This technique demonstrates the utility of a priority queue beyond simple queue management.
In Prim's algorithm, a min-priority queue is used to select the next edge that connects a vertex in the currently built spanning tree to a vertex outside of it. The queue stores the edges weighted by their cost and always allows the algorithm to quickly select the edge with the minimum weight. This ensures the spanning tree is constructed with the lowest possible total edge weight.
In operating systems, a priority queue is used to manage the ready queue of processes awaiting execution by the CPU. Each process is assigned a priority level, and the operating system uses the queue to select the highest-priority process to run next. This system ensures critical, urgent tasks are executed immediately, optimizing resource utilization and system responsiveness.
Implementing a priority queue with an unordered linked list allows $O(1)$ insertion (at the head). However, finding and deleting the highest-priority element requires scanning the entire list, resulting in a worst-case time complexity of $O(n)$. This makes the unordered linked list inefficient for large datasets, where frequent extraction of the highest-priority item is necessary.
In Huffman coding, a min-priority queue stores the forest of trees (initially individual character nodes) weighted by their frequency. The queue repeatedly extracts the two nodes with the smallest frequencies and combines them to form a new parent node. This process, repeated until one tree remains, builds the optimal Huffman tree, which minimizes the average code length for compression.
While a heap is the most common and most efficient implementation for a priority queue in practical computer science, it is not the only way. A priority queue is an abstract data type (ADT), and its underlying structure can be an array, a linked list, or a Binary Search Tree (like a Treap or Red-Black Tree), though these alternatives are often less time-efficient than a binary heap.
The 'heapify' process is a crucial step used to maintain the heap property after an insertion or deletion in a heap-based priority queue. After an element is added or the root is removed, 'heapify-up' or 'heapify-down' is performed to move the element to its correct position, ensuring the highest or lowest priority item (depending on the heap type) remains at the root.
Priority queues are fundamental in discrete-event simulation systems. They manage a list of events scheduled to occur at various future times. The queue holds these events prioritized by their time of occurrence. By always processing the event with the smallest timestamp (highest priority), the simulation can accurately model the passage of time and event sequence.
When a Binary Search Tree (BST) is used to implement a priority queue, insertion in the worst case can degrade to $O(n)$ if the input is already sorted, causing the tree to become heavily skewed (a linked-list like structure). For a self-balancing BST (like an AVL or Red-Black Tree), both insertion and deletion maintain an efficient $O(\log n)$ worst-case time complexity.
The order of insertion primarily determines the final order only for elements that share the exact same priority value, following the FIFO rule for ties. For elements with distinct priorities, the order of insertion is irrelevant, as the priority queue's structure will always reorder them based on their assigned priority value, ensuring the highest-priority element is at the front.
A Double-Ended Priority Queue (DEPQ) is an enhanced priority queue that allows for efficient retrieval and deletion of both the maximum-priority element and the minimum-priority element. This structure is typically implemented using a special heap structure like a Min-Max Heap and is useful in scenarios where you need fast access to both the most urgent and the least urgent task.
840 articles published
Rohit Sharma is the Head of Revenue & Programs (International), with over 8 years of experience in business analytics, EdTech, and program management. He holds an M.Tech from IIT Delhi and specializes...
Speak with Data Science Expert
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources