Heaps & priority queues
Computer Science · Data structures
Question 1 of 10
0In Java’s PriorityQueue, poll() removes:
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
Heaps & priority queues explained
A heap is a tree-shaped structure that gives fast access to its smallest (or largest) item, and a priority queue is a collection from which items are always removed in order of priority. Heaps are the usual way to build a priority queue.
A binary heap is a complete binary tree. In a min-heap every parent is less than or equal to its children, so the smallest value sits at the root.
The tree can be stored in an array without pointers. The root is at index 0, the children of index are at and , and the parent of index is at .
To insert, add the value at the end and swap it upward while it is smaller than its parent. To remove the minimum, move the last value to the root and swap it downward with its smaller child. Both take time, because the tree height is about .
Worked example
Start with the min-heap [2, 5, 3, 9, 6, 4] and insert 1.
- Place 1 at the end, index 6. Its parent is at index , which holds 3.
- Since , swap them: index 2 now holds 1 and index 6 holds 3.
- The parent of index 2 is index 0, which holds 2. Since , swap again.
The heap is now [1, 5, 2, 9, 6, 4, 3]. Two swaps were needed, which matches the height of the tree, .
What you will practise
103 multiple-choice questions (Easy, Medium, Hard). Each answer is followed by an explanation.
Example questions
- A min-heap has the smallest element at the:
- A heap is stored in an:
- Removing the minimum from a min-heap takes:
- Priority queues are often built from:
- The heap property requires parents to be:
- Inserting an element into a binary heap takes, in the worst case:
- A priority queue returns its elements in order of:
- In a max-heap, the largest element is always found at the:
…and 95 more.