Theory
A priority queue is a data structure where each element has a priority and elements are processed according to that priority rather than simply by insertion order. Heaps are commonly used to implement priority queues efficiently.
Example
const tasks = [
{ name: "Low", priority: 3 },
{ name: "High", priority: 1 },
{ name: "Medium", priority: 2 }
];
tasks.sort((a, b) => a.priority - b.priority);
console.log(tasks[0].name);
Expected Output
High
Practice
Create a priority queue for tasks with different priorities.
Interview Questions
- What is a priority queue?
- How is it different from a normal queue?
- What data structure can implement a priority queue?
- Where are priority queues used?