Consider the following Rust code using a max-heap priority queue. What will be printed?
use std::collections::BinaryHeap;
fn main() {
let mut pq = BinaryHeap::new();
pq.push(10);
pq.push(5);
pq.push(20);
pq.push(1);
while let Some(val) = pq.pop() {
print!("{} ", val);
}
}Remember that Rust's BinaryHeap is a max-heap by default, so the largest element comes out first.
The BinaryHeap in Rust is a max-heap, so popping elements returns the largest first. The elements pushed are 10, 5, 20, and 1. Popping them prints 20, then 10, then 5, then 1.
Choose the property that a priority queue guarantees about its elements.
Think about what 'priority' means in a priority queue.
A priority queue always allows quick access to the element with the highest priority (largest or smallest depending on implementation). It does not guarantee full sorting or insertion order.
Analyze the following Rust code snippet. What error will it cause when compiled?
use std::collections::BinaryHeap;
fn main() {
let mut pq = BinaryHeap::new();
pq.push("apple");
pq.push("banana");
pq.push(10);
}Rust's BinaryHeap requires all elements to be of the same type and comparable.
The code tries to push both &str and integer types into the same BinaryHeap. Rust requires all elements to have the same type and implement Ord. This causes a compile-time type mismatch error.
Given a priority queue initially empty, the following operations are performed:
- push 15
- push 30
- pop
- push 10
- pop
How many elements remain in the priority queue?
Track the queue size after each operation carefully.
Operations:
push 15 → size 1
push 30 → size 2
pop (removes 30) → size 1
push 10 → size 2
pop (removes 15) → size 1
So, 1 element remains.
Rust's BinaryHeap is a max-heap by default. This code uses std::cmp::Reverse to simulate a min-heap. What will it print?
use std::collections::BinaryHeap;
use std::cmp::Reverse;
fn main() {
let mut pq = BinaryHeap::new();
pq.push(Reverse(40));
pq.push(Reverse(10));
pq.push(Reverse(30));
pq.push(Reverse(20));
while let Some(Reverse(val)) = pq.pop() {
print!("{} ", val);
}
}Reverse reverses the order, so the smallest element comes out first.
Using Reverse wraps values so BinaryHeap treats them as reversed order, effectively making it a min-heap. Popping returns 10, 20, 30, then 40.
