Priority Queue
Time Complexity
C++ Algorithms
Data Structures
Computational Efficiency

Time complexity of a Priority Queue in C

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

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:

  1. Insertion (`push`): Inserts a new element into the priority queue.
  2. Deletion (`pop`): Removes the element with the highest priority.
  3. Peek (`top`): Retrieves (but does not remove) the element with the highest priority.
  4. Size: Returns the number of elements in the priority queue.
  5. 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:

OperationTime ComplexityDescription
Insert (push)O(logn)O(\log n)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)O(logn)O(\log n)Removal involves replacing the root with the last element and "bubbling down" to restore heap properties.
Peek (top)O(1)O(1)Accessing the element with the highest priority (the root) can be done in constant time.
SizeO(1)O(1)The size is maintained as a class member, thus giving O(1)O(1) access.
EmptyO(1)O(1)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++:


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.