What is a Priority Queue and How Does it Work?

πŸ’‘ Concept Name

Priority Queue – A special type of queue where each element is associated with a priority, and the element with the highest priority is served first.

πŸ“˜ Quick Intro

Unlike a regular queue (FIFO), a priority queue serves elements based on their priority. It can be implemented using arrays, linked lists, heaps (commonly used), or binary search trees.

🧠 Analogy / Short Story

Imagine a hospital emergency room. Patients are treated based on the severity of their condition (priority), not on their arrival time. A patient with a heart attack will be treated before someone with a sprained ankle.

πŸ”§ Technical Explanation

  • πŸ”’ Each element has a priority value.
  • ⬆️ Elements with higher priority are dequeued before lower priority ones.
  • βš–οΈ If two elements have the same priority, the order of insertion is used (FIFO).
  • πŸ›  Often implemented using a min-heap (lowest value = highest priority) or max-heap (highest value = highest priority).
  • ⏱ Insert: O(log n), Remove: O(log n) using heaps.

🎯 Purpose & Use Case

  • βœ… Task scheduling in operating systems.
  • βœ… Dijkstra’s shortest path algorithm.
  • βœ… Huffman encoding in compression.
  • βœ… Managing bandwidth in routers (high priority packets).

πŸ’» Real Code Example

public class PriorityQueueItem
{
    public string Name { get; set; }
    public int Priority { get; set; }
}

public class PriorityQueue
{
    private List<PriorityQueueItem> queue = new();

    public void Enqueue(string name, int priority)
    {
        queue.Add(new PriorityQueueItem { Name = name, Priority = priority });
        queue = queue.OrderByDescending(x => x.Priority).ToList(); // Max priority first
    }

    public string Dequeue()
    {
        if (queue.Count == 0) return "Queue is empty";
        var item = queue[0];
        queue.RemoveAt(0);
        return item.Name;
    }
}

// Example usage
var pq = new PriorityQueue();
pq.Enqueue("Low Task", 1);
pq.Enqueue("High Task", 5);
Console.WriteLine(pq.Dequeue()); // Output: High Task

❓ Interview Q&A

Q1: What is a priority queue?
A: A data structure where each element has a priority, and elements are served based on priority rather than insertion order.

Q2: How is a priority queue different from a regular queue?
A: In a priority queue, elements with higher priority are dequeued before lower priority elements.

Q3: What are common implementations of priority queues?
A: Binary heaps, Fibonacci heaps, and balanced binary search trees.

Q4: What is the typical time complexity for insertion in a binary heap priority queue?
A: O(log n).

Q5: What is the time complexity for extracting the highest priority element?
A: O(log n).

Q6: Can priority queues handle elements with the same priority?
A: Yes, they can, usually served in insertion order or arbitrary order depending on implementation.

Q7: What are some applications of priority queues?
A: Task scheduling, Dijkstra’s shortest path algorithm, and Huffman coding.

Q8: What happens if a priority queue is implemented using an unsorted array?
A: Insertion is O(1) but extraction becomes O(n).

Q9: How does a max-heap represent a priority queue?
A: The root holds the highest priority element.

Q10: Are priority queues stable?
A: Not necessarily; stability depends on implementation.

πŸ“ MCQs

Q1. What determines element order in a priority queue?

  • Insertion order
  • Element priority
  • Alphabetical order
  • Random order

Q2. How does a priority queue differ from a normal queue?

  • Serves FIFO
  • Serves highest priority first
  • Random access
  • LIFO order

Q3. What is a common implementation of priority queues?

  • Array
  • Linked list
  • Binary heap
  • Stack

Q4. What is insertion time complexity in a binary heap?

  • O(1)
  • O(log n)
  • O(n)
  • O(n log n)

Q5. What is extraction time complexity in a binary heap?

  • O(1)
  • O(log n)
  • O(n)
  • O(n log n)

Q6. Can priority queues handle duplicate priorities?

  • No
  • Yes
  • Sometimes
  • Never

Q7. Name an application of priority queues.

  • Sorting
  • Dijkstra's algorithm
  • Hashing
  • Searching

Q8. What is extraction complexity if using an unsorted array?

  • O(1)
  • O(log n)
  • O(n)
  • O(n log n)

Q9. In max-heap based priority queue, where is highest priority?

  • At leaf
  • At root
  • Random
  • Middle

Q10. Are priority queues always stable?

  • Yes
  • No
  • Sometimes
  • Depends on data

πŸ’‘ Bonus Insight

.NET 6+ includes PriorityQueue<TElement, TPriority> in System.Collections.Generic, which simplifies working with priority queues using built-in types.

πŸ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

Learn More About Data Structures πŸ“š

What is a Data Structure and Why is it Important? πŸ‘‰ Learn More
Linear vs Non-linear Data Structures πŸ‘‰ Learn More
Arrays vs Linked Lists πŸ‘‰ Learn More
Advantages & Disadvantages of Arrays πŸ‘‰ Learn More
Singly Linked List Explained πŸ‘‰ Learn More
Singly vs Doubly Linked List πŸ‘‰ Learn More
Circular Linked List & Its Use Cases πŸ‘‰ Learn More
Reversing a Linked List πŸ‘‰ Learn More
Stack vs Queue πŸ‘‰ Learn More
Circular Queue Explained πŸ‘‰ Learn More
Queue Overflow & Underflow πŸ‘‰ Learn More
Applications of Stacks πŸ‘‰ Learn More
Priority Queue Explained πŸ‘‰ Learn More
Deque vs Queue πŸ‘‰ Learn More
Implement Stack Using Queues πŸ‘‰ Learn More
Implement Queue Using Stacks πŸ‘‰ Learn More
Trees in Data Structures πŸ‘‰ Learn More
Binary Trees Explained πŸ‘‰ Learn More
Binary Search Tree vs Binary Tree πŸ‘‰ Learn More
Insert & Delete in BST πŸ‘‰ Learn More
Tree Traversals (Inorder, Preorder, Postorder) πŸ‘‰ Learn More
Level Order Traversal πŸ‘‰ Learn More
Balanced Binary Tree πŸ‘‰ Learn More
AVL Trees Explained πŸ‘‰ Learn More
Red-Black Trees πŸ‘‰ Learn More
B-tree vs BST πŸ‘‰ Learn More
Heaps in Data Structures πŸ‘‰ Learn More
Min-Heap vs Max-Heap πŸ‘‰ Learn More
Implementing Heap Using Arrays πŸ‘‰ Learn More
Applications of Heaps πŸ‘‰ Learn More
Tries & Word Searching πŸ‘‰ Learn More
Graphs Explained πŸ‘‰ Learn More
Adjacency Matrix vs List πŸ‘‰ Learn More
BFS vs DFS πŸ‘‰ Learn More
Detecting Cycle in Graph πŸ‘‰ Learn More
Directed Acyclic Graph (DAG) πŸ‘‰ Learn More
Topological Sorting πŸ‘‰ Learn More
Dijkstra’s Algorithm πŸ‘‰ Learn More
Prim’s vs Kruskal’s Algorithm πŸ‘‰ Learn More
Union-Find / Disjoint Set πŸ‘‰ Learn More
Hash Tables Explained πŸ‘‰ Learn More
Hash Collision Handling πŸ‘‰ Learn More
Open Addressing vs Chaining πŸ‘‰ Learn More
Load Factor in Hashing πŸ‘‰ Learn More
Static vs Dynamic Data Structures πŸ‘‰ Learn More
Segment Trees πŸ‘‰ Learn More
Share:

Tags:


Feedback Modal Popup