#1 India's Top IT Training Institute

×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Queues

Priority Queue in Data Structure — Implementation, Types & More

A Priority Queue is an abstract data type in which each element has an associated priority. Elements are served not in the order they were added, but based on their priority — the highest (or lowest) priority element is served first.

Types

  • Max Priority Queue: the element with the highest priority is served first.
  • Min Priority Queue: the element with the lowest priority is served first.

Implementation Using a Binary Heap

Priority queues are most commonly implemented using a binary heap, which allows insertion and extraction of the highest/lowest priority element in O(log n) time.

import heapq

# Min-priority queue (Python's heapq is a min-heap by default)
pq = []
heapq.heappush(pq, (2, "task B"))
heapq.heappush(pq, (1, "task A"))
heapq.heappush(pq, (3, "task C"))

while pq:
    priority, task = heapq.heappop(pq)
    print(priority, task)   # prints in order 1, 2, 3

Complexity

OperationTime (Heap-based)
InsertO(log n)
Extract min/maxO(log n)
Peek min/maxO(1)

Applications

  • Dijkstra's and Prim's algorithms for graph traversal.
  • Task scheduling based on priority/deadline.
  • Huffman coding for data compression.

Ready to master Data Structures & Algorithms?

Learn DSA hands-on with mentor-led sessions, real interview practice, and placement support.

Explore Course