Hash Tables

Learn how hash tables store and find keys in constant expected time. See how a hash function turns a key into an array index, how separate chaining and open addressing handle collisions, and why the load factor and resizing keep operations fast. Compare expected, amortized and worst-case cost, choose keys that hash correctly, and use Python's sets and dictionaries to solve problems such as duplicate detection, counting and grouping in linear expected time.

IntermediateLesson 5 of 10 in Data Structures and Algorithms Course

What you will learn

  1. Describe the operations that sets and maps support, how a hash function turns a key into an array index, and why collisions are unavoidable.
    • Describe sets, maps and the direct-access idea
      Name the operations of sets and maps, compare their cost in lists and sorted arrays, and see how indexing an array by the key itself leads to hashing.
    • Turn a key into a table index with a hash function
      Explain what a hash function must do and should do, compress a hash code into a table index, and see why collisions start long before the table is full.
    • Hash strings and compound keys
      Compute a polynomial string hash step by step, see why simple sums fail, and combine the fields of a key made of several parts.
  2. Keep the colliding keys of each slot in their own list, trace insert, find and delete by hand, and implement a chained hash map in Python.
    • Insert, find and delete in a chained table
      Trace the operations of a separate-chaining table and relate the length of its chains to the load factor.
    • Build a chained hash map in Python
      Write a small map class with buckets, put, get and remove, then test it against Python's own dict.
  3. Store every entry in the table array itself, follow probe sequences to insert and find keys, and delete keys without breaking later searches.
    • Store and find keys with linear probing
      Trace insertions and searches in a linear-probing table and explain how clusters form.
    • Compare quadratic probing and double hashing
      Use probe sequences that jump instead of stepping by one, and check that a sequence can reach enough slots.
    • Delete keys from an open-addressing table
      Explain why emptying a slot breaks later searches, and delete correctly with tombstones or by reinserting the rest of a cluster.
  4. Control the load factor by resizing, tell expected, amortized and worst-case cost apart, and see how random hash functions protect against bad inputs.
    • Track the load factor and resize the table
      Decide when to grow or shrink a table, rehash every key into the new array, and show why doubling keeps inserts cheap on average.
    • Tell expected cost from worst-case cost
      State the assumptions behind constant-time hash-table operations, compute expected probe counts from the load factor, and recognize the inputs that make operations linear.
    • Use random hash functions to avoid worst cases
      Explain how an attacker can force collisions, and how universal hashing and random per-run seeds make bad inputs unlikely.
  5. Choose valid keys, use Python's sets and dictionaries with an accurate picture of their costs, and solve common problems in linear expected time.
    • Choose and design hashable keys
      Decide which values can be keys, keep hashing consistent with equality in your own classes, and avoid keys that change.
    • Use Python sets and dictionaries and know their costs
      Apply the core operations of set and dict and the helpers in the collections module, with their costs and ordering rules.
    • Solve problems with sets and maps
      Recognize problems where a set or map turns a quadratic search into a linear one, write the solution, and know when an ordered structure fits better.

Hash Tables study guide

5 chapters

1

From keys to array positions

Fast lookup starts with the question a collection must answer: membership in a set or a value associated with a map key. Direct access shows how an integer key can name its own array position, while hashing extends that idea to a much larger key universe. The function must respect equality and distribute keys well. String and compound-key examples show how to compute a useful code without losing the order or identity information that matters.

1.1 Sets, maps, and direct access

A set stores distinct keys. A map, also called a dictionary or associative array, connects each distinct key to a value. A set can tell you whether a room ID exists; a map can return that room's booking. Both support insertion, lookup, and deletion. Assigning a new value to an existing map key replaces its old value.

Choose operations before storage

Sets and maps are abstract data types: they describe behavior. A hash table and a balanced search tree are different ways to implement that behavior. Python's set and dict use hash tables, as do Java's HashSet and HashMap.

The choice of storage changes the cost of the operations. Here, n is the number of stored keys.

StorageFindInsert or delete
Unsorted listWorst-case Θ(n)A set must search to prevent duplicates; finding a deletion target is linear
Sorted arrayWorst-case Θ(log⁡n)Worst-case Θ(n) because entries shift
Direct-access arrayWorst-case O(1)Worst-case O(1)

Binary search is already optimal among methods that learn about keys only by comparing them: distinguishing among n keys needs Ω(log⁡n) comparisons in the worst case. Hashing gains speed by computing an address from a key's value.

Use the key as an index

A direct-access array reserves one position for every possible key. With integer keys from 0 to u−1, the entry for key k goes directly at index k. No search is needed.

For rooms numbered 0 through 499, a booking table can be:

booked = [False] * 500
booked[317] = True
is_booked = booked[317]
booked[317] = False

The four operations create the table, book a room, read its status, and cancel the booking. The Boolean values distinguish an available room from a booked room. Each access after initialization takes constant time, but the array occupies space for all 500 rooms.

That space cost is Θ(u), even if only three rooms are booked. For ten-letter lowercase words, the possible-key universe has 2610≈1.41×1014 members. Reserving a slot for every possible word is impractical when only a few thousand words are needed.

Compress the address space

A hash table allocates m slots, usually proportional to the number of stored keys. A hash function sends a key into the range 0 through m−1. This allows a large key universe to share a manageable array.

Compression introduces collisions: unequal keys can get the same index. A complete design therefore needs a way to keep and find every colliding key. Chaining stores several entries in a bucket; open addressing searches other slots.

The array's positions express hash placement, not sorted order. Finding the smallest key or every key in a range generally requires scanning the entries. Python dictionaries remember insertion order separately; insertion order still does not sort the keys.

Key Takeaways

  • A set stores distinct keys; a map stores one value per distinct key.
  • Direct access gives worst-case constant-time operations at the cost of space for the entire key universe.
  • Hashing compresses a large universe into a smaller array and must handle collisions.
  • Hash placement does not keep keys sorted.

1.2 From hash codes to valid indices

A hash code is an integer computed from a key. A table compresses that integer to one of its m indices, often with h(k) mod m. In Python, the expression is hash(key) % m. Distinguish the integer hash code from the final table index: different hash codes can still give the same remainder.

Correctness comes before distribution

A usable hash function must stay stable while its key is stored, and equal keys must have equal hash codes. Otherwise insertion and a later lookup can choose different paths for the same logical key.

Unequal keys may have equal hashes. A function returning 0 for every key follows the equality rule, but gives terrible performance. For speed, computing the hash should be cheap and the keys in use should spread evenly across the slots. The table must compare actual keys to confirm a match.

A collision occurs when two different keys get the same table index. If the universe has more keys than the table has slots, the pigeonhole principle guarantees that some possible keys collide. A partly empty table is no protection against this: under uniform independent placement, 23 keys in 365 slots already have about a 50.7% chance of at least one collision. For 10 keys in 100 slots the probability is about 37.2%.

Match the remainder method to the keys

For the division method, the index is k mod m. Consider keys 10, 20, 30, 40, and 50.

Table sizeIndices in insertion order
73, 6, 2, 5, 1
100, 0, 0, 0, 0

The second table has more slots but worse placement. The shared factor in the keys defeats the remainder method. A standard choice for this simple method is a prime size away from powers of 2 or 10. A prime is useful here; it does not repair a hash function that always returns the same code.

With m=2p, taking a remainder selects only the lowest p bits. Every multiple of 64 therefore lands at 0 in a 64-slot table. Libraries can still use power-of-two capacities by mixing or using more hash bits. OpenJDK's HashMap mixes upper hash bits into lower ones; CPython's dictionary brings higher bits into later probes.

Handle negative codes correctly

Python's remainder with positive m is already in the valid index range. For example:

-2 % 7  # 5

Java's % can return a negative result for a negative input. Math.floorMod(h, m) gives a valid nonnegative index when m is positive. Another common construction is (h & 0x7fffffff) % m, which clears the sign bit before taking the remainder.

Avoid Math.abs(h) % m in Java. The most negative 32-bit integer has no positive counterpart in the same type, so Math.abs(Integer.MIN_VALUE) remains negative. This is a correctness problem even if ordinary test keys never expose it.

Key Takeaways

  • Equal keys must hash equally, and stored keys need stable hashes.
  • A collision concerns the final index; unique hash codes do not guarantee unique indices.
  • Good distribution depends on the function, the table size, and the keys together.
  • Power-of-two remainders keep only low bits unless the design mixes or later uses other bits.
  • Python handles negative codes with a positive modulus; Java can use Math.floorMod.

1.3 Hashing ordered sequences of fields

Adding character codes is a tempting string hash, but addition loses order. The words "stop" and "pots" both sum to 454. In fact, every anagram has the same sum, and short strings occupy a narrow range of sums. A useful string hash lets each character's position affect the result.

Treat a string as a number

A polynomial hash uses a base R. For character codes c0,…,cL−1, it computes:

h=c0RL−1+c1RL−2+⋯+cL−1.

Earlier characters get higher powers. Java's String.hashCode() uses base 31 with 32-bit arithmetic that wraps on overflow. The character values in Java are UTF-16 code units; for the basic Latin examples here, they match the familiar character codes.

Horner's rule avoids calculating powers separately. Start at zero, then multiply the running hash by the base and add the next code:

def string_index(text, modulus):
    h = 0
    for char in text:
        h = (31 * h + ord(char)) % modulus
    return h

This example uses Python character values. It illustrates the recurrence; it is not Python's built-in string hash.

Work through "cat"

The codes for "cat" are 99, 97, and 116. Without intermediate remainders:

  1. Read "c": 31(0)+99=99.
  2. Read "a": 31(99)+97=3166.
  3. Read "t": 31(3166)+116=98262.

The final value is also Java's hash code for "cat". To work modulo 101 throughout, the running values are 99, 35, and 90. For the last step, 31(35)+116=1201 and 1201 mod 101=90. Taking remainders after each step preserves the final remainder while keeping intermediate numbers small.

Order matters: "act" gives 96402 before reduction and 48 modulo 101. The different result comes from changing which character receives each positional weight. A polynomial hash can still collide; preserving order removes the systematic anagram failure of a simple sum.

Include the fields that define a key

The same idea applies to a compound key such as a point or a (name, year) pair. Combine field hashes in order, for example by repeatedly computing 31h+hash⁡(field). Python's tuple hashing already combines fields, so a custom class can return hash((self.name, self.year)).

A hash built from only one equality field can be correct but poorly distributed. Hashing names by their first letter puts every name beginning with "S" together. Using a field that equality ignores is more dangerous: equal objects could receive different hashes and become unreachable through an equal lookup key.

Hashing a fresh string of length L reads its characters and costs O(L). Constant-time table claims assume bounded-size keys and cheap equality. Python and Java cache a string object's computed hash, so hashing that same object again avoids the full computation; comparing long equal strings can still require reading their contents.

Key Takeaways

  • Horner’s rule updates a running hash by multiplying by the base and adding the next character.
  • Taking the remainder at every step preserves the final modular result.
  • Combine compound-key fields in order and keep hashing consistent with equality.
  • Fresh long strings add a key-length cost to table operations.
2

Separate chaining in practice

Colliding keys can share a bucket without losing their separate identities. A search needs only the chosen bucket, but it must compare the actual keys inside it. Following insertions, updates, misses, and deletions makes the load factor concrete. A short Python implementation then connects those traces to independent bucket lists, distinct-key counts, missing-key behavior, and rehashing when the array grows.

2.1 Keeping colliding entries in buckets

In separate chaining, each table slot holds a collection of entries. That collection is its chain, and the slot is often called a bucket. Every entry belongs to the bucket selected by its key's hash. Different keys can share a bucket without replacing one another.

Follow the same route for every operation

To find a key, compute its bucket index and compare the keys in that chain. A match is a hit; the end of the chain is a miss. An empty bucket gives a miss without any key comparisons.

Insertion scans the chain too. An equal key means a map should replace its value, while a set should leave its membership unchanged. Only a new key adds an entry. Deletion locates and removes the matching entry from its chain; no other bucket needs repair.

Trace a table by hand

Use seven buckets and the index k mod 7. Append each new entry at the end of its chain. Inserting 50, 700, 76, 85, 92, 73, and 101 produces:

BucketKeys, in chain order
0700
150, 85, 92
2empty
373, 101
4empty
5empty
676

Finding 92 computes index 1, then compares against 50, 85, and 92: three comparisons. Finding 64 also chooses bucket 1, but all three comparisons fail. Finding 30 chooses empty bucket 2 and makes no key comparisons. The hash calculation still takes time even for that empty-chain search.

Now put a new value for key 85. The entry stays in bucket 1 and the number of stored keys stays seven. Deleting 50 leaves the chain [85, 92], so a later search for 92 needs two comparisons. These operations show why a collision is different from equality: sharing a bucket determines where to search, while comparing keys determines which entry to use.

Relate chain length to load

The load factor is α=n/m: stored entries divided by buckets. This table has load factor 1. Its chain lengths are 1, 3, 0, 2, 0, 0, and 1, which average exactly 1. The average is not a maximum: one chain is three entries long despite the low overall load.

With uniform independent bucket choices, an unsuccessful search compares against about α keys. Including hashing and bucket access gives expected cost Θ(1+α). A successful search makes about 1+α/2 comparisons. Suitable hashing and resizing that bounds the load factor give expected constant-time lookup and deletion; insertion is expected amortized constant time because it can trigger a rebuild.

Chaining allows α>1 because a bucket can hold several entries. The table remains correct at high load, but chains become longer. In the worst case all keys occupy one chain and a lookup is linear.

Chains can be Python lists, linked lists, or more elaborate structures. OpenJDK's HashMap can convert sufficiently crowded buckets into balanced trees. This improves resilience to collisions, while ordinary chain analysis explains the basic design.

Key Takeaways

  • Find, insert, and delete all begin with the key’s bucket.
  • A map updates an equal key; a collision between unequal keys preserves both entries.
  • Chaining allows a load factor greater than 1.
  • Under uniform hashing, chain search costs expected Θ(1 + α), including the hash and bucket access.
  • Compare actual keys, not just their hash codes.

2.2 A small chained map in Python

A chained map needs separate bucket lists, a count of distinct keys, and a rule for choosing a bucket. The implementation below raises KeyError for a missing lookup, like dictionary indexing. It uses Python's hash, so its keys follow Python's hashability contract.

Build independent buckets
class ChainedMap:
    def __init__(self, capacity=4):
        if capacity < 1:
            raise ValueError("capacity must be positive")
        self.buckets = [[] for _ in range(capacity)]
        self.size = 0

    def _index(self, key):
        return hash(key) % len(self.buckets)

    def get(self, key):
        for stored, value in self.buckets[self._index(key)]:
            if stored == key:
                return value
        raise KeyError(key)

    def put(self, key, value):
        bucket = self.buckets[self._index(key)]
        for pair in bucket:
            if pair[0] == key:
                pair[1] = value
                return
        bucket.append([key, value])
        self.size += 1
        if self.size > len(self.buckets):
            self._resize()

    def remove(self, key):
        bucket = self.buckets[self._index(key)]
        for i, pair in enumerate(bucket):
            if pair[0] == key:
                bucket.pop(i)
                self.size -= 1
                return
        raise KeyError(key)

    def _resize(self):
        old = self.buckets
        self.buckets = [[] for _ in range(2 * len(old))]
        self.size = 0
        for bucket in old:
            for key, value in bucket:
                self.put(key, value)

    __getitem__ = get
    __setitem__ = put
    __delitem__ = remove

    def __len__(self):
        return self.size

    def __contains__(self, key):
        return any(stored == key
                   for stored, _ in self.buckets[self._index(key)])

The comprehension constructs a new list each time. [[]] * capacity would repeat references to one list: appending to one bucket would change every bucket. In contrast, [False] * 500 works for the booking example because assigning an array element replaces a reference to an immutable Boolean.

Trace updates and misses

Starting with four buckets, put keys 3, 7, and 10 with values "c", "g", and "j". For these small nonnegative integers in CPython, the hash equals the integer. Keys 3 and 7 share bucket 3; key 10 goes to bucket 2. Putting (3, "C") replaces the value for 3, giving bucket 3 the pairs [[3, "C"], [7, "g"]]. The size remains three. get(7) checks two pairs and returns "g".

The loop in remove returns immediately after removal, so it never continues iterating a modified list. A method that removes several entries should first collect their positions or iterate over a copy.

Python's own d.get(key, default) returns a default on a miss and does not insert it. That differs from this class's get. A stored None is still a real value; membership or a unique sentinel distinguishes it from absence.

Rebuild and test

The growth rule here is a maximum load factor of 1. Resizing doubles the bucket count and reinserts every entry. Some indices stay the same, while others change: from 8 to 16 buckets, key 6 stays at 6 but key 14 moves from 6 to 14. Copying whole buckets to their old positions breaks later lookups.

Test overwrites, colliding keys, deletion, missing keys, and growth. A strong check performs the same random operations on this class and a dict, comparing values, membership, exceptions, and sizes after each operation. The special methods also allow normal syntax such as m[3], m[3] = "C", del m[3], and len(m).

Key Takeaways

  • Create independent buckets with a comprehension.
  • Only inserting a new key increases size; overwriting does not.
  • Return immediately after removing an entry during a bucket scan.
  • A resize reinserts entries using the new bucket count.
  • Test a custom map against a dict, including collisions and missing keys.
  • Distinguish a stored None from an absent key.
3

Searching with probe sequences

Open addressing puts entries inside the table array and follows a reproducible path when the home slot is occupied. Linear probing makes that path easy to trace, while quadratic probing and double hashing show how jumps affect clustering and coverage. Deletion adds another challenge: a slot must remain traversable if another key relies on it. Worked paths connect the empty-slot stopping rule to tombstones and cluster repair.

3.1 Linear probing and clusters

Open addressing keeps each entry directly in the table array. Each slot holds at most one entry. When a key's first slot is occupied, its probe sequence tells the table which slots to try next. Insertion and lookup must follow the same sequence.

Walk along the array

With linear probing, probe number i visits (h(k)+i) mod m, starting at i=0. The first index is the key's home slot. After the last array position, the sequence wraps to slot 0.

Insertion examines each visited slot. An equal key means update its value; a different key means keep probing; an empty slot means store the new entry. Lookup follows the same path until it finds the key or an empty slot. A mismatch at the home slot does not establish absence.

The empty-slot stopping rule follows from insertion: if a key had been inserted along that path, it would have occupied the first available slot. It could not have passed a slot that is still empty. Deletion needs special handling to preserve that reasoning.

Build a cluster step by step

Take 11 slots, use k mod 11, and insert 22, 1, 13, 11, 24, and 33.

KeyHomeSlots examinedFinal slot
22000
1111
13222
1100, 1, 2, 33
2422, 3, 44
3300, 1, 2, 3, 4, 55

A probe is one slot examination, including the empty slot that ends a miss. Finding 33 takes six probes. Finding missing key 44 starts at 0 and reaches empty slot 6 after seven probes. Finding missing key 2 starts at 2 and visits slots 2 through 6, taking five probes.

Now suppose a key has home slot 10 and that slot is taken. Its next probe is 0, then 1. Forgetting wrap-around either misses a stored key or tries to access beyond the array.

Why long runs attract more keys

A run of occupied adjacent slots is a cluster. In linear probing, any new key whose home lies inside the run travels to its end. Different home slots therefore extend the same cluster, and adjacent runs can merge. This feedback is primary clustering. The six occupied slots in the example form one cluster even though the keys have several different homes.

Linear probing accesses neighboring memory, which works well with processor caches. At moderate load it can be faster in practice than chaining. Its weakness is the steep rise in search cost as the table fills.

Because each live entry needs a slot, n≤m and α=n/m≤1. New-key insertion cannot succeed in a completely full table. A robust implementation bounds a search by the sequence's coverage, so a full table does not cause an endless loop. Normal designs resize well before this boundary, leaving enough empty slots for short searches.

Key Takeaways

  • Linear probing examines consecutive slots and wraps to index 0.
  • Lookup continues past unequal keys and stops at a matching key or a genuinely empty slot.
  • Count the final empty slot as a probe on an unsuccessful search.
  • Primary clustering lets different home slots contribute to one growing run.
  • Open addressing needs spare slots for efficient insertion and search.

3.2 Probe sequences that jump

Linear probing is simple, but its consecutive runs create primary clustering. Quadratic probing and double hashing spread collisions along different paths. The sequence must be reproducible for lookup, and its coverage matters: a table can have empty slots that a badly chosen sequence never reaches.

Compare the formulas

For probe number i=0,1,2,…:

MethodSlot visitedMain tradeoff
Linear(h(k)+i) mod mNearby memory accesses; primary clustering
Quadratic(h(k)+i2) mod mBreaks consecutive runs; may miss slots
Double hashing(h1(k)+ih2(k)) mod mKey-dependent jumps; needs a valid second hash

The quadratic formula here is the square-offset version. Other quadratic formulas have different coverage rules.

Trace quadratic placement

Use 11 slots and home index k mod 11. Insert 22, 1, and 13 directly at 0, 1, and 2. Key 11 has home 0: its offsets 0, 1, and 4 lead to slots 0, 1, and 4, so it lands at 4. Key 24 has home 2 and lands at 3. Key 33 starts at 0 and tries 0, 1, 4, then 9, where it lands.

The keys jump away from a consecutive run. However, every key with the same home follows the same square-offset sequence. This is secondary clustering.

Square offsets do not cover an entire table. Modulo 8 they produce only 0, 1, and 4, so a home-0 key cannot reach the other five slots. For an odd prime size m, the first (m+1)/2 probes are distinct. Thus a table less than half full has a reachable empty slot. For 11 slots, the six reachable offsets are 0, 1, 3, 4, 5, and 9; their visit order begins 0, 1, 4, 9, 5, 3.

Make the step depend on the key

Double hashing uses a second hash as the jump size. With m=11, take h1(k)=k mod 11 and h2(k)=7−(k mod 7). After placing 22, 1, and 13 at 0, 1, and 2:

  • Key 11 has step 3: slots 0, then 3; it lands at 3.
  • Key 24 has step 4: slots 2, then 6; it lands at 6.
  • Key 33 has step 2: slots 0, 2, then 4; it lands at 4.

Keys with one home can now take different paths. A second hash does not guarantee different steps for every pair, but it avoids forcing all same-home keys onto one sequence.

The step must be nonzero and coprime to the table size: the two numbers share no factor greater than 1. A step of 4 modulo 8 alternates between only two slots. With prime size 11, every step from 1 through 10 visits every slot; with a power-of-two size, every odd step does so.

Double hashing trades an extra hash calculation and scattered memory accesses for better spread. All three methods need controlled load and correct deletion. If the table size or probe rule changes, reinsert the entries so later searches follow their actual placement paths.

Key Takeaways

  • Quadratic probing avoids primary clustering but retains secondary clustering.
  • Square-offset probing with an odd prime size finds an empty slot below half load.
  • Double hashing uses a key-dependent step that must be nonzero and coprime to the capacity.
  • Empty slots are useful only if a key’s probe sequence can reach them.
  • Changing the capacity or probe rule requires reinsertion.
  • Linear probing favors nearby memory accesses; double hashing favors spread.

3.3 Deleting without breaking lookup

An empty slot tells an open-addressing search that its key is absent. Deletion must preserve that evidence. Simply erasing a stored entry can create an empty slot in the middle of another key's search path, causing a false miss.

See the broken path

In an 11-slot linear-probing table, slots 0 through 5 hold 22, 1, 13, 11, 24, and 33. The home index is k mod 11. Key 24 has home 2 but is stored at 4 because slots 2 and 3 were taken when it arrived.

If deleting 13 turns slot 2 into empty, finding 24 stops immediately at slot 2. Key 24 still exists at slot 4, but lookup cannot reach it.

Mark a tombstone

A tombstone gives the slot a third state: deleted. The table distinguishes it from both a live entry and a genuinely empty slot.

Slot stateFindInsert or update
Live entryCompare keysUpdate if equal; otherwise continue
TombstoneContinueRemember the first reusable position; continue checking
EmptyReport absenceStore at the remembered tombstone, or here if none

After marking slot 2 deleted, finding 24 visits the tombstone, key 11 at 3, and key 24 at 4. The search succeeds.

Insertion must not immediately stop at the first tombstone. An equal key may already exist later along the path. If putting a new value for key 24 inserted a second copy at slot 2, the map would violate its distinct-key rule. First look for an existing match; use the remembered tombstone only after absence is established. If a bounded full probe cycle finds no match or empty slot, a remembered tombstone can still accept a new key.

Rebuild when deleted slots accumulate

Tombstones preserve correctness, but unsuccessful searches pass through them. A table with few live entries can therefore behave like a crowded table. Track live entries and deleted slots separately, and use their combined occupancy when deciding whether a rebuild is needed.

Rebuilding reinserts only live entries into a fresh array. It can clean the table without increasing capacity. CPython dictionaries use deleted markers and remove them during a rebuild. This behavior is specific to CPython.

Repair a linear-probing cluster instead

Linear probing also permits cluster reinsertion. Clear the deleted slot, then remove and reinsert each following live entry until reaching the next empty slot. Removing 13 from the example requires processing 11, 24, and 33 in order:

  1. Key 11, home 0, moves into slot 2.
  2. Key 24, home 2, lands in slot 3.
  3. Key 33, home 0, lands in slot 4.

Slot 5 becomes empty. Finding 24 now takes two probes, at 2 and 3. Reinsertion checks each key's own home; it does not blindly shift every key left. This repair relies on linear probing's consecutive paths and cannot simply be copied to quadratic probing or double hashing.

Chaining has simpler deletion: removing a pair from one chain leaves the paths to all other entries intact. Workloads with many deletions may favor that simplicity.

Key Takeaways

  • Clearing a slot can create a false stopping point for another key.
  • A tombstone preserves a search path and can later be reused.
  • Insertion must check beyond a tombstone for an existing equal key.
  • Rebuilding removes tombstones by reinserting only live entries.
  • Linear probing can repair deletion by reinserting the rest of the cluster.
4

Controlling cost as a table grows

Table speed depends on how keys spread and how much space remains. Load thresholds and geometric growth keep routine operations short, although individual resizes still take substantial work. Expected, amortized, and worst-case bounds describe different aspects of that behavior. Probe estimates show the cost of high load, and random function choices explain how a table can resist a fixed set of deliberately troublesome keys.

4.1 Load factor, growth, and shrinking

As a table fills, chains lengthen or probe paths grow. The load factor α=n/m measures live entries relative to capacity. A growth threshold keeps this ratio under control; the chosen value depends on the collision method and implementation.

Set a growth threshold

Java's HashMap defaults to load factor 0.75. CPython's dictionary keeps at most about two-thirds of its index slots in use. Sedgewick and Wayne's linear-probing implementation grows at half load. These are different designs, not interchangeable universal thresholds.

A default Java HashMap starts with a nominal capacity of 16 buckets. At load factor 0.75, its threshold is 12 entries. Adding a thirteenth distinct key takes it past that threshold and grows capacity to about 32. Java 19 and later provide HashMap.newHashMap(1000) to size a map for an expected number of entries, avoiding growth for that planned workload.

Rehash every live entry

To grow, allocate a fresh array and recompute each entry's placement using the new size. Doubling from 8 to 16 gives:

KeyOld remainderNew remainder
666
14614
30614

Some indices stay unchanged. Others move, so copying bucket 6 wholesale to new bucket 6 would leave keys 14 and 30 unreachable by normal lookup. Open addressing must also rebuild probe placement, and old tombstones should be discarded.

Spread the rebuild cost over insertions

Reinserting n entries costs expected Θ(n) with suitable hashing; severe collisions can make repeated insertion cost Θ(n2). With good distribution, doubling makes the linear rebuilds rare enough for expected amortized constant-time insertion.

Start with eight slots, maximum load 0.75, and grow before inserting a new key that would pass the threshold. Across 100 insertions, growth occurs at insertions 7, 13, 25, 49, and 97. The rebuilds move:

6+12+24+48+96=186

old entries. Each term is twice the previous one. The geometric sum bounds the total movement by fewer than 2n entries for n insertions under this doubling policy. A resize-triggering insert is still individually expensive; amortized describes a sequence, not a latency promise for each operation.

Growing by a fixed increment behaves differently. Starting with 10 slots and adding 10 only when full makes 10,000 insertions move 4,995,000 old entries. Frequent rebuilds of an increasingly large table give quadratic total work.

Leave a gap before shrinking

A table can shrink after many deletions. The textbook linear-probing table halves at one-eighth load and doubles at half load. After shrinking, enough room remains before growth is needed again. Without this gap, alternating insertion and deletion near one boundary could force a rebuild on every operation.

CPython dictionaries do not shrink just because keys are deleted. Their entry storage can retain gaps, making iteration expensive relative to the live size until storage is rebuilt. A lower load factor also consumes more memory; implementations such as Java's HashMap, whose iteration scans capacity as well as entries, can pay more to traverse an oversized table.

Key Takeaways

  • Compute load as live entries divided by capacity; thresholds depend on the implementation.
  • Resizing recomputes every entry’s placement and drops tombstones.
  • Doubling bounds total entry movement by a geometric sum.
  • Expected amortized constant time permits an occasional expected linear-time insertion.
  • Separate growth and shrink thresholds prevent repeated rebuilding near one boundary.
  • Extra empty space has memory and sometimes iteration costs.

4.2 What constant expected time means

Hash-table performance has two sources of variation. Collisions affect how far a search travels; resizing occasionally rebuilds the whole table. Use expected, amortized, and worst-case precisely so a performance claim says which of these effects it covers.

Separate the kinds of bound
BoundWhat it describes
Worst-caseA limit that applies to every allowed input and operation
ExpectedAn average over randomness in the hash function or an explicit model of the keys
AmortizedTotal work over a sequence, expressed per operation

An amortized analysis is not an assumption that inputs are random. In a hash table, the usual insertion claim is expected amortized O(1): hashing supplies the expected bound, while geometric growth spreads rebuilding costs over the sequence.

Constant expected lookup assumes suitable distribution and a bounded load factor. It also assumes hashing and comparing one key take constant time. Fresh strings of length L add up to O(L) work for hashing or comparison, so key length matters even if only one slot is examined.

Compare search costs at the same load

Under uniform independent hashing, a chained-table miss compares against about α keys. A hit compares against about 1+α/2. At load 2, both estimates are about two comparisons. Bucket access and hashing add constant overhead.

For a large linear-probing table with uniformly distributed home positions and no tombstone buildup, the standard approximations are:

E[hit probes]≈12(1+11−α) E[miss or insertion probes]≈12(1+1(1−α)2).

These are expectations, not exact predictions for one particular search.

LoadHit probesMiss or insertion probes
0.51.52.5
0.752.58.5
0.95.550.5

At load 0.75, the remaining fraction is 0.25. For a miss, squaring it gives 0.0625, taking its reciprocal gives 16, and averaging 1 and 16 gives 8.5. Missing-key searches become especially expensive near full capacity because they must find an empty slot.

Recognize the worst case

With h(k)=k mod 10, the 100 keys 0, 10, 20, through 990 all choose bucket 0. A chained lookup can examine all 100 entries. Inserting distinct keys requires checking increasingly long chains, giving quadratic construction time. Open addressing also has linear worst-case search and quadratic construction when keys follow the same probe sequence.

A balanced search tree instead guarantees O(log⁡n) per operation in the worst case and maintains sorted order. Hash tables favor fast expected exact-key access; trees suit ordered queries and stronger per-operation bounds. Python dictionaries preserve insertion order, which does not support a direct next-larger-key query.

Reducing load can shorten searches, but unlimited spare capacity is not free. It costs memory and can slow iteration when the implementation scans the allocated table. Java documents traversal cost proportional to capacity plus entry count.

Key Takeaways

  • Expected cost averages over a stated source of randomness.
  • Amortized cost spreads sequence work; it does not bound every operation separately.
  • Linear-probing misses grow sharply more expensive as load approaches 1.
  • A hash-table search can take linear time in the worst case.
  • Long keys can add hashing and equality costs even with short probe paths.
  • Balanced trees provide sorted access and logarithmic worst-case operations.

4.3 Random choices and collision resistance

A fixed hash function can distribute ordinary data well yet fail on carefully chosen keys. If the universe has more than m(n−1) keys and only m slots, at least one slot receives at least n possible keys. Someone who knows the function can choose a colliding set from that group.

Why adversarial keys matter

Hash flooding supplies many keys designed to collide, such as request-field names stored in a server's map. Searching an ever-growing chain during insertion can turn expected linear construction into quadratic work. The server spends its time comparing keys instead of handling other requests.

Choosing the hash function randomly makes a preselected bad key set less likely to cause this behavior. The random choice must stay stable for the table's lifetime: choosing a new function for each lookup would send it to a different place from insertion.

Choose from a universal family

A family H is universal when every fixed pair of distinct keys has collision probability at most 1/m over a uniformly random choice of function:

Pr⁡h∈H[h(x)=h(y)]≤1/m(x≠y).

The quantifier matters. No one function has to separate every pair. Instead, any fixed pair collides under only a limited fraction of the family's functions.

One standard integer-key family chooses a prime p larger than the keys and at least the table size. Choose a from 1 through p−1 and b from 0 through p−1, then use:

ha,b(k)=((ak+b) mod p) mod m.

The first remainder mixes the key in the larger prime range; the second compresses that result into the table.

For p=17 and m=6, choose a=3,b=4. Key 5 gives 19 mod 17=2, then index 2. Key 11 gives 37 mod 17=3, then index 3. A different choice, a=5,b=2, gives indices 4 and 0. Across all 272 choices of the two parameters, this pair collides 32 times: about 0.118, below 1/6≈0.167.

Move the expectation to the table's choice

With universal hashing and chaining, the expected length of a stored key's chain is at most 1+(n−1)/m. The key itself contributes one entry; each other fixed key contributes collision probability at most 1/m. This works for any fixed set of keys chosen independently of the random function. It does not require the input keys themselves to be random.

Randomization limits systematic collisions; it does not eliminate ordinary ones. Collision resolution and load control remain necessary.

Understand Python's process seed

Python salts str and bytes hashes with a random value chosen when the interpreter starts, enabled by default since Python 3.3. hash("cat") stays stable within a run, while its value can change across runs. PYTHONHASHSEED can fix the seed for reproducible tests. Integer hashes are not salted; hash(42) is 42.

Store the original key when data must persist or move between programs, not its process-specific hash. Set iteration order has no language guarantee and can vary across runs, especially for strings. Dictionary insertion order is a separate guarantee and does not depend on remembering a particular string hash.

Key Takeaways

  • A known fixed hash function can have deliberately chosen bad inputs.
  • A universal family bounds each fixed pair’s collision probability over the random function choice.
  • Universal chaining bounds expected chain length without assuming random input keys.
  • Randomization keeps a stable function within a run and still requires collision handling.
  • Python string and bytes hashes can change between interpreter runs.
5

Choosing keys and solving problems

Using a set or dictionary well means choosing valid keys, understanding the operations, and storing the right information for later steps. Python examples connect the equality-and-hash contract to tuples, custom classes, and frozen dataclasses. Counting, grouping, duplicate detection, and two-sum then show how a remembered answer removes repeated scans, while ordered queries and small integer ranges point to other useful structures.

5.1 Keys whose hashing agrees with equality

A key needs a stable route into its table. In Python, a hashable object has a lifetime-stable hash and supports equality comparison. Whenever two keys compare equal, their hash codes must be equal. The table still compares keys after finding a candidate because unequal keys are allowed to collide.

Check the whole value
ValueCan it be a key?
Integer, float, string, or bytesYes
TupleYes, if every element is hashable
Frozen setYes; its elements are hashable
List, dictionary, or setNo

An immutable outer container does not make every object inside it hashable. hash((1, [2])) raises TypeError because the tuple contains a list. Use (row, col) for a grid coordinate and frozenset(items) for an unordered collection key when its elements are hashable.

Equality also crosses type boundaries. In Python, 1, 1.0, and True compare equal and hash equally. Thus {1: "a", 1.0: "b", True: "c"} has one entry: the first key object remains, with final value "c". Different spellings or types do not necessarily represent different logical keys.

Keep equality fields stable

If a content-based key changes after insertion, its stored location reflects its old hash. A later lookup may compute a new index and miss the entry. Even changes that leave the hash unchanged can break the intended distinct-key behavior if equality changes. Do not modify the fields that define a key's equality while it is stored.

Mutability by itself is not the full test. An ordinary user-defined object has identity-based equality and hashing by default. Changing an unrelated attribute does not change its identity, so it can remain a valid key.

Define custom content-based keys

A class defining __eq__ without __hash__ becomes unhashable in Python. When two point objects should represent the same coordinate, both methods must use the same stable fields. A frozen dataclass provides a concise implementation:

from dataclasses import dataclass

@dataclass(frozen=True)
class Point:
    x: int
    y: int

labels = {Point(2, 3): "start"}
assert labels[Point(2, 3)] == "start"

With the default equality setting, frozen=True generates equality and hashing from the fields and blocks field assignment. All fields must still be hashable and stable. A frozen dataclass holding a list is not a usable hashed key, because freezing the wrapper does not freeze its contents. A plain mutable dataclass generates equality but normally sets its hash to None.

In a manual point class, __hash__ can return hash((self.x, self.y)). Omitting one equality field can cause extra collisions; hashing a field ignored by equality can give equal objects different hashes and break lookup.

Apply the same contract in Java

Java's equals and hashCode must agree too. Overriding equals while keeping identity-based hashCode can make map.get(new Point(2, 3)) fail immediately after an equal point was inserted. Java records generate both methods from their components. Record components also need stable equality and hashes while the record is a key; a reference to a mutable object does not become deeply immutable just because it is a component.

Key Takeaways

  • Hashable keys need stable hashes, and equal keys must hash equally.
  • A tuple is hashable only when every element is hashable.
  • Keep content-based equality fields unchanged while a key is stored.
  • Frozen dataclasses help define keys but do not freeze nested mutable objects.
  • Python treats equal numeric values such as 1, 1.0, and True as one key.
  • Java requires equals and hashCode to agree.

5.2 Using Python sets and dictionaries

Python's set answers membership questions; dict connects keys to values. Their familiar syntax hides hashing, collision resolution, and resizing. Knowing the operations' meaning is as important as knowing their expected cost.

Select the right operation
ExpressionResult or effect
x in s, s.add(x), s.discard(x)Test, add, or remove set membership; discard tolerates absence
k in dTest dictionary keys
d[k]Read a value; raise KeyError if missing
d.get(k, default)Read a value or return a default, without insertion
d.setdefault(k, default)Insert the default if missing and return the stored value
del d[k]Remove an entry; raise KeyError if missing

In CPython, these operations take average O(1) time with suitable keys and O(n) in the worst case. Insertion is also amortized because of growth. Testing v in d.values() scans values and takes linear time; hashing accelerates key lookup, not arbitrary value search.

Building a set from a list costs expected linear time. It is useful before many membership tests. Checking 10,000 IDs against a 10,000-item list can require 108 comparisons. Building a set once replaces those scans with 10,000 expected constant-time lookups, plus construction. For just one membership test, building the set can cost as much as scanning the list.

Count and group

collections.Counter creates a frequency map. For Counter("the cat and the hat and the bat".split()), the counts are 3 for "the", 2 for "and", and 1 each for "cat", "hat", and "bat". Calling .most_common(1) gives [("the", 3)].

defaultdict(list) creates a missing key's empty list on indexed access, so grouping can use groups[key].append(item) without a membership test. It differs from get, which does not create a missing entry.

Combine memberships

For a = {1, 2, 3, 4} and b = {3, 4, 5}:

  • a | b gives {1, 2, 3, 4, 5}: union.
  • a & b gives {3, 4}: intersection.
  • a - b gives {1, 2}: difference.
  • a ^ b gives {1, 2, 5}: symmetric difference.

On average, intersection takes O(min⁡(∣a∣,∣b∣)) time by iterating the smaller set and checking the larger. Union takes O(∣a∣+∣b∣).

Keep order and mutation rules straight

Dictionary insertion order is a Python language guarantee since 3.7. Updating a value leaves its position unchanged; deleting and reinserting a key moves it to the end. list(dict.fromkeys([3, 1, 3, 2, 1])) gives [3, 1, 2], preserving first occurrences. Sets have no defined order. Java's HashMap and HashSet also guarantee no iteration order; LinkedHashMap preserves insertion order.

When adding or deleting dictionary keys in a loop, iterate over list(d) to use a snapshot of the keys. Changing the key set during direct iteration can raise RuntimeError or disrupt traversal. Updating values of existing keys is allowed.

Iteration is linear in live entries when storage is proportional to them. CPython sets scan allocated slots, while dictionaries scan entry storage including deletion gaps. After many deletions, traversal can cost much more than the current live size suggests. Spare capacity and stored entry metadata also make hash tables use more memory than a list of the same items.

Key Takeaways

  • Dictionary membership tests keys; value membership requires a scan.
  • get leaves a missing key absent, while setdefault can insert it.
  • Counter counts items; defaultdict(list) supports grouping.
  • Dictionary insertion order is guaranteed, while set order is not.
  • Use a snapshot when a loop adds or removes dictionary keys.
  • After many deletions, retained storage can make iteration expensive relative to live size.
  • Building a set pays off when it avoids repeated list scans.

5.3 Replacing repeated searches with a map

Many quadratic algorithms repeatedly ask whether an earlier item exists. A set can remember membership; a map can remember an index, count, group, or computed result. One expected constant-time lookup per item often replaces an inner linear scan, reducing total time from quadratic to expected linear with linear extra space.

Detect duplicates
def has_duplicate(items):
    seen = set()
    for x in items:
        if x in seen:
            return True
        seen.add(x)
    return False

The invariant is that seen contains exactly the values from earlier iterations. For 100,000 items, comparing all pairs can take 4,999,950,000 comparisons. The set version processes each item once, using at most 100,000 membership tests and insertions. Replacing seen with a list makes membership linear again and loses the speedup.

Find two distinct positions

For two-sum, store earlier values with their positions:

def two_sum(values, target):
    earlier = {}
    for i, x in enumerate(values):
        needed = target - x
        if needed in earlier:
            return earlier[needed], i
        earlier[x] = i
    return None

For [4, 9, 1, 6, 3] with target 10, the map first stores 4 at index 0, then 9 at index 1. At index 2, value 1 needs 9, so the result is (1, 2). The complement check comes before insertion. With one value 4 and target 8, inserting first would let the element pair with itself.

This map keeps only the latest earlier index for each value. That is enough to find one valid pair, but a task requesting every pair may need a list of indices per value. Choose the stored value to match the question.

Count first, then preserve order

Count items with Counter(items) or counts[x] = counts.get(x, 0) + 1. To find a string's first unique character, count all characters, then scan the original string. For "swiss", the counts are 3 for "s", 1 for "w", and 1 for "i". The second scan finds "w" first. A set alone loses the frequencies needed to distinguish unique and repeated characters.

Group by a canonical key

Anagrams can use their sorted letters as a common key:

from collections import defaultdict

groups = defaultdict(list)
for word in words:
    signature = "".join(sorted(word))
    groups[signature].append(word)

"listen", "silent", and "enlist" share "eilnst". "stone", "notes", and "tones" share "enost"; "cat" has "act". A string or tuple(sorted(word)) is hashable, but the list returned by sorted(word) is not. For words of length L, sorting each signature costs O(Llog⁡L); expected constant-time map access does not remove the work of constructing or hashing the key.

Memoization similarly maps hashable arguments to results, as functools.cache does. Graph searches use a visited set and can store each vertex's neighbors in a map of sets.

Recognize when hashing is a poor fit

A balanced tree or sorted array better supports sorted output, smallest or largest keys, and range queries such as bookings from 10:00 to 12:00. A balanced tree also gives logarithmic worst-case operations. For a small known integer range, direct access can be simpler: counting letters "a" through "z" needs only 26 array counters.

Key Takeaways

  • Store the information each later lookup needs: membership, index, count, group, or result.
  • In two-sum, check the complement before storing the current item.
  • A second pass through the original input preserves the order needed for first-occurrence questions.
  • Canonical grouping keys must be hashable, and constructing them has its own cost.
  • Choose ordered structures for range queries and direct access for small integer universes.

Hash Tables examples

5 Walkthroughs

1

Compute where a key belongs

12 steps
Connect the collection’s job to an array position, then build a string hash one character at a time.
  1. 1
    IntroductionStart with the lookup question

    A set answers “is this key present?” A map answers “what value belongs to this key?” Both can use hashing to avoid searching every entry.

    Follow a room-booking example from direct access to compressed indices, then compute an order-sensitive string hash. The calculation chooses a starting position; it does not replace the equality check that confirms a key.

  2. 2
    ExampleGive each room an address

    Suppose room IDs run from 0 through 499. A direct-access array uses each ID as its own position: booked[317] reads room 317’s status.

    Lookup, assignment, and deletion take worst-case constant time after initialization. The cost is space for all 500 possible IDs, including rooms with no stored booking. Direct access is attractive when the universe is small and dense.

  3. 3
    ConnectionCompress a much larger universe

    Words cannot usually receive their own direct-access slots. Ten lowercase letters already allow roughly 141 trillion possible strings. A small collection of words needs a table sized to the stored entries instead.

    A hash function maps each key to one of those slots. Some keys must share a position, so the design combines fast address computation with a strategy for collisions.

  4. 4
    ChallengeChoose storage for a dense range

    A system tracks membership for IDs 0 through 63 and needs worst-case constant-time access. What simple representation fits, and how many positions does it reserve?

    ---reveal---

    A 64-position Boolean array uses each ID directly as an index. It reserves the entire universe even when few IDs are present. A general hash table adds collision handling that this small range does not need.

  5. 5
    ExplanationSeparate the code from the index

    A hash code is an integer; the table compresses it to a valid index, for example with h(k) mod m. A shared remainder is a collision even if the original codes differ.

    Equal keys must hash equally, and a stored key’s hash must remain stable. A fast function should also spread the actual workload well. Unequal keys can still collide, so lookup must compare the keys themselves.

  6. 6
    ExampleSee why table size matters

    For keys 10, 20, 30, 40, and 50, taking remainders modulo 10 sends every key to 0. Modulo 7, they reach 3, 6, 2, 5, and 1.

    The larger table does worse because its size aligns with the key pattern. Prime sizes are useful for the simple division method. Power-of-two designs need care with low-bit patterns and often mix bits or use higher bits in later probes.

  7. 7
    ChallengeCheck equality and distribution

    A function returns zero for every key and stays unchanged while keys are stored. Does it violate the equality rule, and what problem does it create?

    ---reveal---

    It satisfies the equality rule: equal keys receive equal hashes. Its distribution is terrible because every key starts at one index. A correct collision strategy preserves the entries, but searches can become linear.

  8. 8
    ExplanationRead a string from left to right

    A polynomial string hash gives character positions different weights. Horner’s rule starts with zero and updates h=Rh+c for each character code c.

    Taking a remainder after each update preserves the final modular result while limiting intermediate values. A simple sum lacks the multiplication, so it ignores order and forces anagrams to collide.

  9. 9
    ExampleRead the first two characters of "cat"

    Use base 31 and modulus 101. The character codes for "cat" are 99, 97, and 116. Start at zero.

    After "c", the running value is 31(0)+99=99. After "a", compute 31(99)+97=3166, then reduce to 3166 mod 101=35. The value 35 now carries the weighted contribution of the first two characters into the next update.

  10. 10
    ExampleFinish the string hash

    For the final "t", use the previous reduced value 35: 31(35)+116=1201, and 1201 mod 101=90.

    Without intermediate reduction, the final hash is 98262; its remainder modulo 101 is also 90. The recurrence therefore keeps the needed index information without storing the full growing number. A fresh string still costs time proportional to its length to read.

  11. 11
    ChallengePreserve the identity of a pair

    A key’s equality uses both name and year, but its hash adds their hashes without preserving order. How would you construct a clearer ordered Python key, and why does that help?

    ---reveal---

    Use the tuple (name, year) or hash that tuple in the class. Tuple hashing combines the fields in order while respecting equality. It avoids deliberately throwing away their roles, although collisions remain possible.

  12. 12
    RecapConnect computation to lookup

    Use direct access when a manageable integer universe supplies the address itself. For general keys, hash computation selects an index in a smaller table.

    Check correctness first: equal keys need equal, stable hashes. Then examine distribution, including key patterns, table size, and sequence order. A compressed hash identifies where to begin searching; collision handling and equality identify the actual entry.

2

Build and use a chained map

11 steps
Trace one bucket, implement its operations, and preserve the entries when capacity changes.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionKeep colliding keys together
  2. 2
    ExamplePlace the first four keys
  3. 3
    ExampleFinish the chains
  4. 4
    ExampleCount hits and misses
  5. 5
    ChallengeUpdate and remove
  6. 6
    TipCreate genuinely separate buckets
  7. 7
    ExplanationCount new keys, not assignments
  8. 8
    ExampleRemove one pair safely
  9. 9
    ChallengeCheck a short operation sequence
  10. 10
    ChallengePreserve the bucket invariant during growth
  11. 11
    RecapKeep storage and behavior aligned
3

Follow probe paths and repair deletion

17 steps
Build one table with several probe rules, then see why deleted slots need careful handling.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionA collision becomes a path
  2. 2
    ExampleFill the home slots
  3. 3
    ExampleGrow one consecutive run
  4. 4
    ExplanationUse an empty slot as evidence
  5. 5
    ChallengeWrap a new insertion
  6. 6
    ExampleUse square offsets instead
  7. 7
    Key InsightCheck which slots are reachable
  8. 8
    ExampleLet a second hash choose the step
  9. 9
    ChallengeDiagnose a short cycle
  10. 10
    ExampleCreate a hole and lose a key
  11. 11
    ExplanationKeep a deleted marker
  12. 12
    TipDelay reuse until absence is known
  13. 13
    ChallengeUpdate beyond a tombstone
  14. 14
    ExampleRepair a linear cluster instead
  15. 15
    ConnectionMatch the repair to the path
  16. 16
    ChallengeConnect occupancy to a rebuild
  17. 17
    RecapPreserve the search invariant
4

Explain why a table stays fast

14 steps
Combine load thresholds, geometric rebuilding, search estimates, and randomized hash choices.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionTrack two kinds of work
  2. 2
    ExampleCross the growth threshold
  3. 3
    ExampleRecompute placement during growth
  4. 4
    ExampleAdd the rebuild sizes
  5. 5
    ChallengePrevent repeated shrinking and growth
  6. 6
    ExplanationRead both qualifications
  7. 7
    ExampleCompare high-load misses
  8. 8
    ChallengeIdentify an expensive operation
  9. 9
    ExplanationMove the randomness into the table
  10. 10
    ExampleEvaluate a randomly chosen function
  11. 11
    Key InsightCount expected neighbors
  12. 12
    ChallengeKeep one stable random choice
  13. 13
    ChallengeSeparate two performance diagnoses
  14. 14
    RecapState the promise precisely
5

Use the right key and remember earlier work

16 steps
Check key validity, choose Python operations, and trace a map-based solution with distinct positions.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionDecide what the program must remember
  2. 2
    ExampleInspect a nested key
  3. 3
    ExplanationMake equality and hashing agree
  4. 4
    ChallengeDistinguish identity from contents
  5. 5
    ExampleChoose missing-key behavior
  6. 6
    ConnectionOrder is separate from hashing
  7. 7
    ChallengeAvoid a value scan
  8. 8
    ExplanationKeep an invariant about earlier items
  9. 9
    ExampleProcess the first two values
  10. 10
    ExampleFind the earlier partner
  11. 11
    ChallengeTest the check-before-store rule
  12. 12
    ExampleCount before choosing the first
  13. 13
    ConnectionConstruct a shared grouping key
  14. 14
    TipMutate through a stable snapshot
  15. 15
    ChallengeChoose a structure for the whole task
  16. 16
    RecapStore exactly the information needed

Hash Tables practice questions

50 Practice Questions in 5 sets

Set 1: Keys, collisions, and basic operations10 Practice Questions

Question 1 of 10

A map contains {"cedar": 4}. What is its size after assigning d["cedar"] = 9?
  1. 2
  2. 4
  3. 1
  4. 9
Show answerHide answer
Answer: C
The assignment finds the existing key "cedar" and replaces its value with 9, so there is still one key–value pair. Counting two entries would confuse an update with an insertion; maps store one value for each distinct key.

Question 2 of 10

What does Python evaluate -9 % 5 to?
  1. 1
  2. -4
  3. 4
  4. -1
Show answerHide answer
Answer: A
Python chooses the nonnegative remainder when the modulus is positive: negative nine equals negative two times five plus one. The value negative four follows truncation toward zero, which is how Java’s remainder behaves, but it is not Python’s result.

Question 3 of 10

A polynomial hash starts at zero, uses base 5, and takes remainders modulo 13 after each character. A two-character key has codes 4 and 7. What is its final hash?
  1. 11
  2. 9
  3. 7
  4. 1
Show answerHide answer
Answer: D
The first update gives 4, and the second gives 27 before reduction, leaving remainder 1 modulo 13. Adding the codes gives 11, but that omits the multiplication that gives the first character its positional weight.

Question 4 of 10

A chained table has five buckets and index k % 5. Keys 12, 7, 19, and 22 are appended in that order. How many key comparisons does a search for missing key 27 make?
  1. 1
  2. 3
  3. 2
  4. 4
Show answerHide answer
Answer: B
Key 27 selects bucket 2, which contains 12, 7, and 22 in that order. All three keys must be compared before the miss is known. Counting four would include key 19 even though it belongs to bucket 4 and is never examined.

Question 5 of 10

What goes wrong if a chained map initializes buckets with [[]] * 6?
  1. Each position starts with a different empty list.
  2. Only the first position can accept a new pair.
  3. All six positions refer to one shared list.
  4. The six lists share keys but keep separate values.
Show answerHide answer
Answer: C
List repetition copies references to the inner list, so an append through any bucket appears through all six positions. It does not create six independent lists; a comprehension must construct each bucket separately.

Question 6 of 10

An empty seven-slot table uses linear probing with home k % 7. Insert 6, 13, and 20 in that order. Where is 20 stored?
  1. Slot 0
  2. Slot 1
  3. Slot 2
  4. Slot 6
Show answerHide answer
Answer: B
All three keys have home slot 6. Key 6 occupies 6, key 13 wraps to 0, and key 20 passes both before reaching slot 1. Slot 0 is the tempting result if the second collision is overlooked, but it already holds key 13.

Question 7 of 10

A linear-probing table has a tombstone at slot 4, key 18 at slot 5, and an empty slot 6. Key 18 has home 4. What must putting a new value for 18 do?
  1. Continue to slot 5 and update key 18.
  2. Reuse slot 4 for a second copy of key 18.
  3. Stop at slot 4 and report 18 absent.
  4. Skip slot 5 and insert 18 at slot 6.
Show answerHide answer
Answer: A
The tombstone preserves the path to the existing entry at slot 5, so insertion must continue and update that entry. Reusing slot 4 immediately would create two equal keys. A tombstone is reusable space only after the operation establishes that the key is absent.

Question 8 of 10

A chained table has capacity 20, load limit 0.75, and 15 distinct keys. It doubles when a new insertion passes the limit. What happens when a sixteenth distinct key is inserted?
  1. It stays at 20 buckets and appends one entry.
  2. It grows to 21 buckets and keeps every old index.
  3. It grows to 40 buckets and copies every old chain.
  4. It grows to 40 buckets and rehashes the entries.
Show answerHide answer
Answer: D
The sixteenth entry would make the load 0.8, above 0.75, so the growth rule doubles capacity to 40. Entries need placement under the new modulus. Copying old chains unchanged would leave some keys outside the bucket where future lookups search.

Question 9 of 10

A class compares objects only by code but hashes (code, label). Two objects have equal codes and different labels. Why can a dictionary lookup by the second object fail after inserting the first?
  1. Unequal labels make the objects different keys despite the equality method.
  2. Equal objects can hash differently and take different search paths.
  3. Equal codes force equal tuple hashes regardless of the label field.
  4. A collision makes the later lookup overwrite the earlier stored value.
Show answerHide answer
Answer: B
Equality ignores the label, so the objects are equal keys, but hashing includes it and can produce different codes. The lookup can therefore follow a different path from insertion. Different labels do not make these objects unequal because the class’s equality method uses only code.

Question 10 of 10

An empty dictionary executes value = d.get("oak", 0). What are value and d afterward?
  1. value is 0; d has "oak": 0.
  2. value is None; d is empty.
  3. A KeyError is raised; d is empty.
  4. value is 0; d is empty.
Show answerHide answer
Answer: D
The explicit default 0 is returned because "oak" is absent, and get leaves the dictionary unchanged. Inserting "oak": 0 describes setdefault, not get. Dictionary indexing without a default would instead raise KeyError for this missing key.
Set 2: Probe paths, load, and Python behavior10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A large linear-probing table has uniform home positions, no tombstones, and load 0.8. Using the standard approximation, what is the expected number of probes for a miss?
  1. 3
  2. 5
  3. 25
  4. 13
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Integer keys are all multiples of 32. A table uses the raw key modulo 32 as its index. Why do they all start at slot 0?
  1. The remainder keeps five high bits, all zero.
  2. The remainder keeps five low bits, all zero.
  3. The table has too few slots for any distinct keys.
  4. Every power-of-two table ignores its hash function.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A chained table contains 18 entries in 6 buckets. What is its load factor?
  1. 0.33
  2. 6
  3. 12
  4. 3
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A nine-slot linear-probing table has keys 8, 17, and 26 in slots 8, 0, and 1; all other slots are empty. With home k % 9, how many probes does finding missing key 35 take?
  1. 1
  2. 4
  3. 3
  4. 5
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A table uses square-offset quadratic probing with home 2 and capacity 7. What are the first four probe positions?
  1. 2, 3, 6, 4
  2. 2, 3, 4, 5
  3. 2, 3, 6, 2
  4. 2, 4, 6, 1
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

An open-addressing table of size 12 uses double hashing. A key has home 1 and step 8, and slots 1, 9, and 5 are occupied. Every other slot is empty. Why can this key not be inserted by that sequence?
  1. Its step visits all twelve slots, but in the wrong order.
  2. Its home slot must be empty before any insertion can occur.
  3. Its step cycles through only those three occupied slots.
  4. Its even home index prevents the sequence from wrapping.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A table has 8 live entries and 52 tombstones in 80 slots. Why can unsuccessful lookups remain slow despite the low live load?
  1. They pass deleted markers before reaching empty slots.
  2. They compare every deleted key with every live key.
  3. They stop at the first deleted marker and restart.
  4. They must rebuild the table after each deleted marker.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

What stays constant when Python randomizes string hashes with its normal per-process seed?
  1. A string’s hash across all interpreter runs.
  2. A string set’s order across all interpreter runs.
  3. A string’s hash during one interpreter run.
  4. Every string’s hash being different from every other.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

Starting with d = {"elm": 2, "pine": 5}, execute d["elm"] = 8, then delete "pine" and assign d["pine"] = 6. What does list(d) return?
  1. ["elm", "pine"]
  2. ["pine", "elm"]
  3. ["elm", "elm", "pine"]
  4. ["pine"]
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A two-sum function stores each current value before testing its complement. For [3, 7, 8] and target 14, what false result can it report?
  1. It can pair index 0 with index 0.
  2. It can pair index 1 with index 2.
  3. It can pair index 1 with index 1.
  4. It can pair index 0 with index 2.
Show answerHide answer

Save this lesson to see this answer.

Set 3: Tracing updates and diagnosing failures10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

Why does hash(("cell", [4, 6])) raise TypeError?
  1. The tuple contains an unhashable list.
  2. Tuples holding a string are unhashable.
  3. A tuple key must hold two integers.
  4. Only frozen sets work as compound keys.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A function counts every character, then scans the original string for the first character with count one. What does it return for "leveler"?
  1. "l"
  2. "e"
  3. "v"
  4. "r"
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

An application stores membership for integer IDs 0 through 255, uses most of them, and needs worst-case constant-time checks. What storage fits directly?
  1. A binary-searched sorted array.
  2. An unsorted list of the IDs.
  3. A chained table with any hash.
  4. A 256-element Boolean array.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Why does a string hash based only on adding character codes send "care" and "race" to the same hash value?
  1. Both strings must compare equal as keys.
  2. Any four-letter strings have equal hashes.
  3. Addition loses the order of the characters.
  4. The table must have exactly four slots.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A chained map stores (2, "a") and (6, "b") in four buckets. After updating key 2 and removing key 6, what should its size be?
  1. 1
  2. 0
  3. 2
  4. 3
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

An eight-slot linear-probing table inserts 7, 15, 0, and 8 in that order, with home k % 8. All later slots remain empty. How many probes does a lookup for missing key 16 require?
  1. 2
  2. 4
  3. 3
  4. 5
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

For double hashing with capacity 16, what property must a nonzero step have to reach every slot?
  1. It must be odd.
  2. It must be even.
  3. It must divide 16.
  4. It must equal the home slot.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

An empty seven-slot linear-probing table inserts 5, 12, and 19 using home k % 7. Delete 5 using cluster reinsertion. In which slots do 12 and 19 end up?
  1. 12 at 6; 19 at 0.
  2. 12 at 0; 19 at 1.
  3. 12 at 5; 19 at 0.
  4. 12 at 5; 19 at 6.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A table doubles from 10 to 20 buckets and uses raw integer remainders. Where should keys 4 and 14 be placed after rehashing?
  1. 4 at bucket 4; 14 at bucket 4.
  2. 4 at bucket 4; 14 at bucket 14.
  3. 4 at bucket 8; 14 at bucket 8.
  4. 4 at bucket 14; 14 at bucket 14.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A fixed-capacity chained map gets distinct keys whose hash always returns 0. Its insertion scans for an existing key before appending. What is the total key-comparison cost of inserting n keys?
  1. Θ(1)
  2. Θ(log⁡n)
  3. Θ(n2)
  4. Θ(n)
Show answerHide answer

Save this lesson to see this answer.

Set 4: Choosing designs and explaining their cost10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A map uses a hash function that always returns 11, and correctly compares keys inside a chain. What changes compared with a well-distributed hash?
  1. Lookups remain correct but can become linear.
  2. Different keys overwrite one another automatically.
  3. Lookup is constant because the hash is constant.
  4. Equal keys can no longer be compared correctly.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A key class compares (name, year) for equality but hashes only name. A workload has many years for each of a few names. What diagnosis and change fit?
  1. The hash violates equality; remove year from equality.
  2. The hash is invalid because unequal keys must hash differently.
  3. The hash is valid but crowded; combine both equality fields.
  4. The hash is well spread; increase the value size instead.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Two different keys have equal hash codes in a chained map. What decides whether a lookup has found its key?
  1. Equality of their hash codes alone.
  2. Equality of their associated values alone.
  3. Their positions inside the same bucket.
  4. Equality of the stored key and lookup key.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A chained map doubles its bucket count by copying each old bucket list to the same numbered position. It has raw integer hashes and grows from 6 to 12 buckets with keys 2 and 8 stored. What happens to lookups?
  1. Both keys remain reachable in bucket 2.
  2. Key 2 remains reachable; key 8 is misplaced.
  3. Both keys move to bucket 8 automatically.
  4. Key 8 remains reachable; key 2 is misplaced.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A square-offset quadratic table has prime capacity 13 and six live entries, with no tombstones. Is a reachable empty slot guaranteed for the next new key?
  1. No; quadratic probing must visit all thirteen slots first.
  2. Yes; seven distinct initial probes exceed six occupied slots.
  3. Yes; six entries imply that every home slot is empty.
  4. No; the guarantee applies only at capacity seven.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A chained table doubles when an insertion would pass load 0.5, but halves when a deletion brings load below 0.5, subject to a minimum capacity. Why can alternating updates near the boundary be expensive?
  1. Each shrink can force the next insertion to grow again.
  2. Each update changes every key’s hash code permanently.
  3. Each shrink makes the table’s load permanently zero.
  4. Each insertion must fail after the first shrink.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

What two effects does “expected amortized O(1) insertion” account for in a resizing hash table?
  1. Sorted key order and the cost of returning values.
  2. A constant worst-case chain and a constant-size array.
  3. Randomized collision cost and rebuild cost across updates.
  4. Randomized resize times and the absence of collisions.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A chained table chooses a universal hash randomly into 12 buckets, independently of its 49 fixed keys. What upper bound follows for the expected chain length of a selected stored key, and does it limit every actual chain to that size?
  1. At most 4 in expectation; an actual chain may be longer.
  2. At most 5 in expectation; every actual chain is at most 5.
  3. At most 49/12 in expectation; every actual chain meets it.
  4. At most 5 in expectation; an actual chain may be longer.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A frozen Python dataclass uses default equality and has one field containing a list. What happens when an instance is hashed?
  1. Hashing succeeds because every frozen object is hashable.
  2. Hashing uses only the instance’s identity by default.
  3. Hashing silently converts the list field to a tuple.
  4. Hashing raises TypeError for the list field.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A scan stores positions[x] = i for each item in [5, 8, 5, 5]. A later task needs every occurrence of each value. What information was lost, and what representation keeps it?
  1. Distinct values were merged; map each index to the final value.
  2. Earlier indices were overwritten; map each value to a list of indices.
  3. Input order was reversed; use one set of distinct values.
  4. Repeated values were counted twice; keep only the first index.
Show answerHide answer

Save this lesson to see this answer.

Set 5: Combining invariants and performance tradeoffs10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A collection must repeatedly return the smallest key and keys within a range. What structure naturally supports these queries?
  1. A hash table ordered by hash code.
  2. A balanced binary search tree.
  3. An unsorted list of the keys.
  4. An insertion-ordered dictionary.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

An empty ten-slot linear-probing table inserts 9, 19, 1, and 29 with home k % 10. It then updates key 19. Which slots are examined during that update?
  1. 9, 0, 1
  2. 9, 0, 1, 2
  3. 9, 0
  4. 0, 1
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A seven-slot linear-probing map has tombstones at 5 and 6, key 26 at 0, and an empty slot 1. Key 26 has home 5. Insertion reuses the first tombstone after ruling out an existing key. After updating 26 and then inserting missing key 33, also with home 5, where are they?
  1. 26 stays at 0; 33 occupies 5.
  2. 26 moves to 5; 33 occupies 6.
  3. 26 stays at 0; 33 occupies 1.
  4. 26 moves to 6; 33 occupies 5.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A table grows by a fixed ten slots each time it fills. Why does constructing n entries take quadratic total entry movement?
  1. Every new key hashes to exactly the same index.
  2. Each growth doubles the number of stored keys.
  3. Fixed-increment growth requires sorting before insertion.
  4. Many rebuilds each move an increasingly large prefix.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Two large linear-probing tables have uniform home positions and no tombstones, at loads 0.5 and 0.75. About how many times larger is the second table’s expected miss-probe count?
  1. 1.5 times
  2. 1.67 times
  3. 3.4 times
  4. 4 times
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

An experiment stores only hash(word) values from one Python run and uses them to identify words in another. Why is this unreliable even for ordinary strings?
  1. Every string hash is guaranteed to change on every new run.
  2. Python dictionaries discard all integer hash values at shutdown.
  3. A fixed seed makes every distinct word receive a unique hash.
  4. String hashes can change across runs and unequal words can collide.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A seven-slot linear-probing table uses home k % 7 and stores only 10 at slot 3 and 17 at slot 4. It switches to a newly chosen hash with home (2 * k) % 7 without moving entries. What does lookup for 17 do, and what restores placement under the new function?
  1. It misses at 6; reinsert entries under the new function.
  2. It misses at 6; keeping the new function stable is enough.
  3. It misses at 3; reinsert entries under the new function.
  4. It finds 17 at 4; keeping the new function stable is enough.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

What does {2: "first", 2.0: "second"} contain in Python?
  1. Two entries, one for each numeric type.
  2. One entry with key 2 and value "second".
  3. One entry with key 2 and value "first".
  4. No entries because numeric keys cannot mix types.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

For a = {2, 4, 6} and b = {4, 7}, what does a ^ b produce?
  1. {4}
  2. {2, 4, 6, 7}
  3. {2, 6}
  4. {2, 6, 7}
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A program groups n words of maximum length L by "".join(sorted(word)). Assume ordinary comparison sorting and uncached key hashing. What expected upper bound accounts for building the signatures as well as map access?
  1. O(nLlog⁡L+n)
  2. O(n) regardless of word length
  3. O(nlog⁡n) regardless of word length
  4. O(n2L) even with well-distributed hashes
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

64 Key Terms, each with its definition

A

Abstract data type
An abstract data type defines what operations mean without specifying the storage structure that implements them.
Both a hash table and a balanced tree can implement the same map operations with different costs.
Aliasing
Aliasing occurs when multiple references name the same mutable object, so a change through one reference is visible through the others.
Repeating one empty bucket list makes every array position refer to the same list.
Amortized cost
An amortized cost expresses a sequence’s total work per operation, accounting for expensive operations among many cheaper ones.
Doubling spreads occasional rebuild work over insertions without making each resize-triggering insertion cheap.

B

Balanced search tree
A balanced search tree maintains key order while keeping its height logarithmic, supporting logarithmic worst-case map operations.
A booking range query benefits from sorted navigation that hash placement does not directly supply.
Bucket
A bucket is a table position that holds the entries assigned to one index, often as a list or another searchable collection.
Keys 12 and 17 share a bucket when the index is the integer remainder modulo five.

C

Canonical key
A canonical key is a common representation assigned to items that should belong to the same group, such as sorted letters for anagrams.
The words "east" and "seat" share the signature "aest", which can index one list of words.
Capacity
The capacity of a hash table is its number of buckets or array slots, which combines with the live entry count to determine load.
Doubling capacity lowers occupancy but requires a rebuild because some indices change under the new modulus.
Chain
A chain is the collection of entries in one bucket of a separately chained hash table, searched using actual key equality.
A miss scans the entire chosen chain even when many other buckets contain no entries.
Cluster reinsertion
Cluster reinsertion repairs linear-probing deletion by removing and reinserting following entries up to the next empty slot.
After clearing a slot, each affected key is placed again from its own home instead of blindly shifted left.
Collision
A collision occurs when two different keys are assigned the same table index, requiring a strategy that preserves both entries.
Two room IDs in one bucket still need a key comparison to determine which booking to return.
Complement
A complement in two-sum is the value needed alongside the current value to reach the target, found by subtracting from that target.
With target 17 and current value 6, a lookup for 11 asks whether an earlier item completes the pair.
Compound key
A compound key identifies an entry using several ordered fields whose equality and hashes jointly define the logical key.
A tuple containing a name and year distinguishes entries for the same name in different years.
Coprime integers
Coprime integers share no positive factor greater than one; a double-hashing step coprime to capacity reaches every table position.
Step three visits every slot modulo eight, while step four alternates between just two slots.
Counter
A Counter is a dictionary subclass in Python’s collections module that records how often hashable items appear.
Counting words first makes it possible to report the most frequent word or identify words that occur once.

D

Default dictionary
A default dictionary uses a factory to create the value for a missing key when that key is accessed by indexing.
A defaultdict(list) lets grouping code append an item without first creating the group’s list.
Direct-access array
A direct-access array stores a key’s entry at the array index equal to that integer key, reserving space for the whole key range.
For a known range of 256 IDs, a Boolean array can check membership with one indexed access.
Division method
The division method selects an index by taking a key or hash code modulo the table size, making key patterns relevant to placement.
Multiples of ten all choose slot zero modulo ten, but can spread across a suitable prime-sized table.
Double hashing
Double hashing forms a probe sequence using one hash for the home position and another hash for a key-dependent step size.
Two keys can share a home but jump along different paths when their second hashes differ.

E

Equality–hash contract
The equality–hash contract requires equal objects to have equal hashes, while permitting collisions between objects that compare unequal.
Hashing a label ignored by equality can send equal custom keys to different lookup paths.
Expected cost
An expected cost is a probability-weighted operation cost under stated randomness, such as a table’s randomly selected hash function.
An expected constant-time lookup can still take linear time for an unlucky collision pattern.

F

Frequency map
A frequency map associates each distinct item with its number of occurrences, retaining information that a membership set discards.
After counting a string, scan its original order to locate the first character with frequency one.
Frozen dataclass
A frozen dataclass blocks field reassignment and, with default equality, generates field-based hashing that requires hashable fields.
A point with stable integer coordinates can be a value-based dictionary key through dataclass(frozen=True).

G

Geometric growth
Geometric growth increases capacity by a constant factor, such as doubling, so cumulative rebuild movement stays linear over insertions.
Old-entry move counts of 6, 12, 24, and 48 form a geometric sequence with a bounded total relative to size.

H

Hash caching
Hash caching stores a computed hash on an object so later hash requests for that same unchanged object avoid recomputing it.
Python and Java cache string hashes, although comparing long equal strings can still read their contents.
Hash code
A hash code is the integer produced by hashing a key before the table compresses it to its finite range of array indices.
Different hash codes can still choose one bucket when their remainders match at the current capacity.
Hash flooding
Hash flooding deliberately supplies many colliding keys so a hash table performs excessive comparison work and slows its surrounding service.
Repeated insertion into one long chain can turn linear expected construction into quadratic work.
Hash function
A hash function computes an integer from a key, respecting equality and stability so a table can locate the key consistently.
A function returning zero is correct for equality but puts every key on the same collision path.
Hash seed
A hash seed is a value that selects a hashing behavior for a process or table and remains stable while stored keys rely on it.
Python normally chooses a random string-hash seed at startup, so hashes can differ across interpreter runs.
Hashability
Hashability is the ability to provide a lifetime-stable hash and equality comparisons while ensuring equal objects receive equal hashes.
A tuple containing a list is unhashable because the list cannot supply a valid element hash.
Home slot
A home slot is the first position in a key’s probe sequence, computed from the key’s hash before collision resolution.
A key stored after a collision may sit several positions beyond its home, so lookup must continue.
Horner’s rule
Horner’s rule evaluates a polynomial hash by repeatedly multiplying the running result by the base and adding the next element.
Taking a remainder after each update keeps the intermediate hash small without changing the final remainder.

I

Identity-based equality
Identity-based equality treats objects as equal only when they are the same object, allowing stable hashing despite unrelated attribute changes.
Two ordinary class instances with matching attributes remain separate keys unless equality is customized.
Immutability
Immutability prevents an object’s own contents from changing, but an immutable wrapper can still reference a mutable object.
A frozen dataclass does not turn a list held in one of its fields into an immutable sequence.
Insertion order
Insertion order is the sequence in which distinct keys entered a collection; Python dictionaries preserve it independently of hash placement.
Updating a key’s value keeps its position, while deleting and reinserting that key puts it last.
Intersection
The intersection of two sets contains exactly the elements present in both, found by checking the smaller set against the larger.
The expression a & b identifies IDs shared by two collections without preserving duplicates.

K

Key universe
A key universe is the set of all possible keys a structure may need to represent, including keys not currently stored.
Ten-letter lowercase strings have a huge universe even if a particular word collection is small.

L

Lazy deletion
Lazy deletion removes a key logically by leaving a deleted marker in its slot, postponing cleanup until later reuse or rebuilding.
A table can have low live occupancy but many long searches after deleted markers accumulate.
Linear probing
Linear probing resolves a collision by checking successive table positions modulo capacity until a match or suitable empty slot is found.
A probe after the last array index wraps to zero and continues along the same logical path.
Load factor
The load factor is the number of live entries divided by capacity, measuring average chain length or live slot occupancy.
Twenty keys in ten chained buckets give load two, which is valid because buckets can hold several entries.

M

Map
A map is a collection that associates one value with each distinct key and supports looking up, updating, and deleting entries.
A room map can associate each room ID with its current booking instead of only recording membership.
Map interface
A map interface is the set of operations exposed for key–value storage, such as lookup, assignment, membership, deletion, and length.
Python special methods let a custom chained map support m[key] and len(m) like a dictionary.
Memoization
Memoization stores previously computed results under keys representing their inputs so repeated requests can reuse those results.
Python’s functools.cache needs hashable arguments because it uses them to identify stored results.

O

Open addressing
Open addressing resolves collisions by storing entries directly in array slots and following probe sequences to find available positions.
A seven-slot table can hold at most seven live entries because each entry needs its own slot.
Overwrite
An overwrite replaces the value associated with an existing map key while leaving the number of distinct stored keys unchanged.
Putting a second booking value under the same room ID updates the entry without increasing map size.

P

Polynomial hash
A polynomial hash combines sequence elements with powers of a base so each position affects the resulting integer.
The hashes of "cat" and "act" can differ because each character receives a different positional weight.
Primary clustering
Primary clustering is the growth of consecutive occupied runs in linear probing as keys with homes within a run extend it.
Keys with different home slots can join one cluster when each is pushed to the same run’s end.
Probe
A probe is one examination of a table slot during insertion, lookup, or deletion, including the empty slot that ends a miss.
Visiting three occupied slots followed by an empty one costs four probes, not three.

Q

Quadratic probing
Quadratic probing selects collision positions using a quadratic offset, such as the square of the probe number, modulo capacity.
With size eight, square offsets reach only three positions even when the other slots are empty.

R

Rehashing
Rehashing rebuilds a table by placing each live entry into a fresh array using the current capacity and collision rules.
A same-capacity rebuild can remove tombstones without increasing the space allocated to the table.
Resize thrashing
Resize thrashing is repeated rebuilding caused by updates that cross growth and shrink boundaries too close together.
Alternating one insertion and one deletion can repeatedly resize a table with poorly separated thresholds.

S

Secondary clustering
Secondary clustering occurs when keys sharing a home position follow the same quadratic probe sequence and compete for its slots.
Square offsets spread collisions beyond one run but still give same-home keys the same path.
Sentinel
A sentinel is a distinct marker value used to represent a special state, such as a missing lookup that must differ from stored data.
An object() default lets code distinguish a missing key from a key whose stored value is None.
Separate chaining
Separate chaining resolves collisions by storing a collection of entries in each bucket and searching that collection for a key.
Deleting one pair from a bucket leaves the lookup paths through every other bucket unchanged.
Set
A set is a collection of distinct keys that supports membership testing, insertion, and deletion without associated values.
A visited set lets a graph search recognize a vertex it has already processed.
Set difference
A set difference contains the elements of its left operand that do not occur in its right operand, so operand order matters.
The expression a - b finds IDs in a that are missing from b; reversing it asks a different question.
Shrink threshold
A shrink threshold is a low-occupancy boundary at which a table reduces capacity, normally separated from its growth boundary.
Shrinking at one-eighth load leaves room for later insertions before a half-load growth trigger.
Symmetric difference
The symmetric difference of two sets contains elements present in exactly one operand, excluding their shared elements.
The expression a ^ b combines the two one-sided differences while removing every shared ID.

T

Table index
A table index is a valid array position selected from a key’s hash, commonly by taking the remainder modulo table capacity.
A positive capacity of seven makes Python’s hash(key) % 7 produce an index from zero through six.
Tombstone
A tombstone marks a deleted open-addressing slot that searches must pass and insertions may reuse after checking for an existing key.
A deleted home slot cannot end lookup when another key may have been displaced beyond it.

U

Uniform hashing assumption
The uniform hashing assumption models each key as independently equally likely to choose any bucket, supporting expected-cost analysis.
It predicts average chain length but does not say every chain has exactly that length.
Union
The union of two sets contains every element present in either set, with each element appearing only once.
Combining two ID sets with a | b keeps shared IDs as single elements in the result.
Universal hash family
A universal hash family limits each distinct fixed pair’s collision probability to one divided by capacity over a random function choice.
The guarantee concerns a fixed pair and the choice of function, not collision-free placement for every key.

V

Visited set
A visited set records which graph vertices an algorithm has already encountered, allowing expected constant-time repeated-visit checks.
A traversal can avoid processing the same vertex again by testing membership before adding new work.

W

Worst-case cost
A worst-case cost bounds the largest cost over allowed inputs or states, without relying on an average or favorable random choice.
A basic hash-table lookup can scan all keys, while a balanced tree guarantees logarithmic lookup.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started