Priority Queue Introduction and Concept in DSA Javascript - Time & Space Complexity
We want to understand how the time needed to use a priority queue changes as we add or remove items.
How does the work grow when the queue gets bigger?
Analyze the time complexity of the following code snippet.
class PriorityQueue {
constructor() {
this.items = [];
}
enqueue(element) {
this.items.push(element);
this.items.sort((a, b) => b.priority - a.priority);
}
dequeue() {
return this.items.pop();
}
}
This code adds elements with priorities and keeps the queue sorted so the highest priority is last.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Sorting the array after each insertion.
- How many times: Sorting happens every time we add an element.
Sorting takes more time as the queue grows because it compares many elements.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 to 40 comparisons |
| 100 | About 700 to 800 comparisons |
| 1000 | About 10,000 to 12,000 comparisons |
Pattern observation: The work grows faster than the number of items, roughly multiplying by a bit more than the size each time.
Time Complexity: O(n^2)
This means adding an item takes longer as the queue grows, roughly proportional to the square of the number of items.
[X] Wrong: "Adding an item is always quick because we just push it to the array."
[OK] Correct: After adding, sorting the whole array takes time that grows with the number of items, so adding is not just a simple push.
Knowing how priority queues work and their time costs helps you explain your choices clearly and shows you understand how data grows in real problems.
"What if we used a heap instead of sorting the array every time? How would the time complexity change?"
Practice
Priority Queue and a regular queue?Solution
Step 1: Understand queue behavior
A regular queue removes elements in the order they arrive (FIFO).Step 2: Understand priority queue behavior
A priority queue removes elements based on their priority, not just arrival order.Final Answer:
Elements are dequeued based on priority, not just order of arrival -> Option BQuick Check:
Priority Queue = priority-based removal [OK]
- Thinking priority queue works like a normal queue
- Assuming priority queue only stores numbers
- Confusing priority queue with stack
Solution
Step 1: Check class syntax
class PriorityQueue { constructor() { this.items = []; } } uses correct ES6 class syntax with constructor initializing an array.Step 2: Check other options
function PriorityQueue() { this.items = {}; } uses function but initializes an object, not array; let PriorityQueue = () => { this.items = []; } uses arrow function incorrectly for class; var PriorityQueue = new Array(); assigns array directly, not a class.Final Answer:
class PriorityQueue { constructor() { this.items = []; } } -> Option CQuick Check:
Correct class syntax = class PriorityQueue { constructor() { this.items = []; } } [OK]
- Using arrow functions as classes
- Initializing items as object instead of array
- Assigning array directly without class
class PriorityQueue {
constructor() {
this.items = [];
}
enqueue(element, priority) {
this.items.push({element, priority});
this.items.sort((a, b) => a.priority - b.priority);
}
dequeue() {
return this.items.shift().element;
}
}
const pq = new PriorityQueue();
pq.enqueue('A', 2);
pq.enqueue('B', 1);
pq.enqueue('C', 3);
console.log(pq.dequeue());
What will be printed?Solution
Step 1: Analyze enqueue operations
Elements are added with priorities: A(2), B(1), C(3). After each enqueue, array is sorted by priority ascending.Step 2: Analyze dequeue operation
Dequeue removes first element (lowest priority number). After sorting, order is B(1), A(2), C(3). So dequeue returns 'B'.Final Answer:
'B' -> Option AQuick Check:
Lowest priority dequeued first = 'B' [OK]
- Assuming FIFO order instead of priority
- Confusing priority sorting order
- Forgetting to return element, not object
class PriorityQueue {
constructor() {
this.items = [];
}
enqueue(element, priority) {
this.items.push({element, priority});
}
dequeue() {
return this.items.shift().element;
}
}
What is the main problem with this code?Solution
Step 1: Check enqueue method
Enqueue adds elements but does not sort by priority.Step 2: Check dequeue method
Dequeue removes first element, but without sorting, priority order is not guaranteed.Final Answer:
It does not sort items by priority before dequeue -> Option DQuick Check:
Missing sorting causes wrong dequeue order [OK]
- Assuming shift() removes highest priority
- Ignoring sorting requirement
- Confusing object vs array storage
Solution
Step 1: Understand operation needs
Priority queue needs fast insertion and removal of highest priority element.Step 2: Compare data structures
Array requires sorting after insertion (slow). Linked list maintains order but slow for priority. Stack removes last inserted only. Binary heap supports insert and remove in O(log n) time efficiently.Final Answer:
Binary heap, because it provides efficient insert and remove operations -> Option AQuick Check:
Binary heap = efficient priority queue [OK]
- Choosing array and ignoring sorting cost
- Confusing stack with priority queue
- Ignoring time complexity of operations
Ready to prove it?
Pass the test and this pattern moves unknown
