Hash tables/maps

Computer Science · Data structures

Question 1 of 10

0

    Which data structure is best for counting how many times each letter appears in a text?

    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.

    Hash tables/maps explained

    A hash table, also called a hash map or dictionary, stores key and value pairs. A hash function turns each key into a number, and that number gives the slot where the value is stored. To look up a key, the program computes its hash and goes straight to that slot instead of checking every item.

    Two keys can produce the same slot, which is called a collision. Common ways to handle collisions are chaining, which keeps a small list in each slot, and open addressing, such as linear probing, which tries the next free slot. A good hash function spreads keys evenly, so that lookups, inserts and deletes take constant time on average, written O(1)O(1). If many keys collide, the time can grow to O(n)O(n) in the worst case.

    A common mistake is to think a hash table keeps its keys in sorted order. In the basic structure its order depends on the hash values, so it is not sorted (some languages keep insertion order, but still not sorted order).

    Worked example

    Store the keys 12, 7 and 22 in a table with 5 slots, numbered 0 to 4. The hash function is key mod 5, and collisions are handled by linear probing: if a slot is taken, try the next one, wrapping round to slot 0 if needed.

    1. 12=2×5+212 = 2 \times 5 + 2, so 12 goes in slot 2.
    2. 7 gives slot 2, but slot 2 is taken. Slot 3 is free, so 7 goes there.
    3. 22 gives slot 2, which is taken, and slot 3, which is also taken. Slot 4 is free, so 22 goes there.

    The table is now: slot 0 empty, slot 1 empty, slot 2 holds 12, slot 3 holds 7, slot 4 holds 22.

    What you will practise

    104 multiple-choice questions (Easy, Medium, Hard). Each answer is followed by an explanation.

    Example questions

    • A hash table stores:
    • Lookup in a hash table is typically:
    • A hash function:
    • Collisions occur when:
    • Chaining resolves collisions by:
    • With a well-sized table and a good hash function, inserting a new key-value pair takes on average:
    • In a hash map, each stored value is accessed through its:
    • Which Java class is a hash-table-based implementation of the Map interface?

    …and 96 more.