Time complexity of a Priority Queue in C
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Priority Queues are an abstract data structure that allows for efficient access to the smallest (or largest) element in a set. They are utilized in a variety of algorithms, such as Dijkstra's and Prim's algorithms, where it's essential to repeatedly remove elements of highest or lowest priority quickly. In C++, the Standard Template Library (STL) provides the `std::priority_queue` class template which implements a max-heap by default. Understanding the time complexity of operations on a priority queue is crucial for leveraging its power in solving computational problems efficiently.
Basic Operations
A priority queue supports a set of standard operations, each with a specific time complexity:
- Insertion (`push`): Inserts a new element into the priority queue.
- Deletion (`pop`): Removes the element with the highest priority.
- Peek (`top`): Retrieves (but does not remove) the element with the highest priority.
- Size: Returns the number of elements in the priority queue.
- Empty: Checks if the priority queue is empty.
Let's explore the time complexities of these operations when implemented as a binary heap, the standard underlying structure of a `std::priority_queue` in C++.
Time Complexity Analysis
The time complexity of operations in a priority queue implemented using a binary heap is as follows:
| Operation | Time Complexity | Description |
Insert (push) | Adding an element involves placing it at the next available position (maintaining a complete binary tree) and then "bubbling up" to preserve heap properties. | |
Remove (pop) | Removal involves replacing the root with the last element and "bubbling down" to restore heap properties. | |
Peek (top) | Accessing the element with the highest priority (the root) can be done in constant time. | |
| Size | The size is maintained as a class member, thus giving access. | |
| Empty | Checking emptiness involves a simple comparison, hence constant time. |
Example in C++
Below is a simple example demonstrating how to use the `std::priority_queue` in C++:

