Heaps & priority queues

Computer Science · Data structures

Question 1 of 10

0

    In Java’s PriorityQueue, poll() removes:

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    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 ii are at 2i+12i+1 and 2i+22i+2, and the parent of index ii is at ⌊(i−1)/2⌋\lfloor (i-1)/2 \rfloor.

    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 O(log⁡n)O(\log n) time, because the tree height is about log⁡2n\log_2 n.

    Worked example

    Start with the min-heap [2, 5, 3, 9, 6, 4] and insert 1.

    1. Place 1 at the end, index 6. Its parent is at index ⌊(6−1)/2⌋=2\lfloor (6-1)/2 \rfloor = 2, which holds 3.
    2. Since 1<31 < 3, swap them: index 2 now holds 1 and index 6 holds 3.
    3. The parent of index 2 is index 0, which holds 2. Since 1<21 < 2, swap again.

    The heap is now [1, 5, 2, 9, 6, 4, 3]. Two swaps were needed, which matches the height of the tree, ⌊log⁡27⌋=2\lfloor \log_2 7 \rfloor = 2.

    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.