Priority queue with heaps in Data Structures Theory - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
We want to understand how the time needed to manage a priority queue using a heap changes as the number of items grows.
Specifically, how fast can we add or remove items when the queue gets bigger?
Analyze the time complexity of the following heap operations.
// Insert an element into a max-heap
function insert(heap, value) {
heap.push(value) // Add at the end
let i = heap.length - 1
while (i > 0 && heap[parent(i)] < heap[i]) {
swap(heap, i, parent(i)) // Move up if bigger than parent
i = parent(i)
}
}
// Remove the max element from a max-heap
function extractMax(heap) {
if (heap.length === 0) return null
let max = heap[0]
heap[0] = heap.pop() // Replace root with last element
if (heap.length > 0) {
heapify(heap, 0) // Fix heap property downwards
}
return max
}
This code shows how we add a new item and remove the largest item in a heap-based priority queue.
Look at the loops that move elements up or down the heap.
- Primary operation: Swapping elements while moving up (insert) or down (extractMax) the heap.
- How many times: At most, the number of swaps equals the height of the heap, which grows as the heap grows.
As the number of items n increases, the heap becomes taller, but not by much.
| Input Size (n) | Approx. Operations (swaps) |
|---|---|
| 10 | About 4 swaps |
| 100 | About 7 swaps |
| 1000 | About 10 swaps |
Pattern observation: The number of swaps grows slowly, roughly with the height of the heap, which increases logarithmically as the input size grows.
Time Complexity: O(log n)
This means adding or removing an item takes time that grows slowly, roughly proportional to the number of times you can halve the number of items.
[X] Wrong: "Adding or removing items in a heap is as slow as scanning all items, so it takes O(n) time."
[OK] Correct: The heap structure keeps items partially sorted in a tree shape, so operations only need to move along the height of the tree, not all items.
Understanding heap operations and their time complexity shows you can work with efficient data structures that handle priority tasks quickly, a useful skill in many coding challenges.
"What if we used a simple unsorted list instead of a heap? How would the time complexity for adding and removing the highest priority item change?"
Practice
Solution
Step 1: Understand priority queue functionality
A priority queue is designed to always provide quick access to the element with the highest priority.Step 2: Recognize heap role in priority queue
Heaps maintain the highest priority element at the top, enabling fast retrieval.Final Answer:
To quickly access the highest priority element -> Option BQuick Check:
Priority queue = fast highest priority access [OK]
- Confusing priority queue with sorting
- Thinking it stores elements alphabetically
- Assuming it only sorts ascending
Solution
Step 1: Understand insertion in max-heap
New elements are added at the end (bottom level) to maintain complete tree property.Step 2: Restore heap property by heapifying up
Heapify up moves the new element up if it has higher priority than its parent.Final Answer:
Add element at the end and heapify up -> Option DQuick Check:
Insert = end + heapify up [OK]
- Adding element at root instead of end
- Heapifying down after insertion
- Confusing heapify directions
Solution
Step 1: Remove max element and replace with last
Remove 40 (root), replace with last element 10: [10, 30, 20, 15]Step 2: Heapify down to restore max-heap
Compare 10 with children 30 and 20; swap with 30 (largest child): [30, 10, 20, 15]. Then compare 10 with 15; swap with 15: [30, 15, 20, 10].Final Answer:
[30, 15, 20, 10] -> Option AQuick Check:
Extract max + heapify down = [30, 15, 20, 10] [OK]
- Not swapping correctly during heapify down
- Forgetting to replace root with last element
- Confusing heapify up with heapify down
extract_max(heap): max = heap[0] heap[0] = heap.pop() heapify_up(heap, 0) return max
Solution
Step 1: Understand extract max steps
Extract max removes root, replaces it with last element, then restores heap by heapifying down.Step 2: Identify incorrect heapify call
The code calls heapify_up, but after replacing root, heapify_down is needed to push the new root down if smaller.Final Answer:
Should call heapify_down instead of heapify_up -> Option CQuick Check:
Extract max = heapify down [OK]
- Confusing heapify directions
- Popping from wrong end
- Misordering operations
Solution
Step 1: Identify highest priority tasks
Tasks with priority 5 are Task1 and Task3, highest among all.Step 2: Understand heap extraction order for equal priorities
Max-heap extracts highest priority; if priorities tie, extraction order depends on insertion order or heap structure. Usually, the first inserted among equals is extracted first.Final Answer:
Task1, because it appears first among highest priority tasks -> Option AQuick Check:
Highest priority + insertion order = Task1 first [OK]
- Assuming any highest priority task is extracted first
- Ignoring insertion order for ties
- Picking lower priority tasks first
