Hash Tables
IntermediateLesson 5 of 10 in Data Structures and Algorithms Course
What you will learn
- 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 ideaName 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 functionExplain 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 keysCompute a polynomial string hash step by step, see why simple sums fail, and combine the fields of a key made of several parts.
- Describe sets, maps and the direct-access idea
- 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 tableTrace the operations of a separate-chaining table and relate the length of its chains to the load factor.
- Build a chained hash map in PythonWrite a small map class with buckets, put, get and remove, then test it against Python's own dict.
- Insert, find and delete in a chained table
- 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 probingTrace insertions and searches in a linear-probing table and explain how clusters form.
- Compare quadratic probing and double hashingUse probe sequences that jump instead of stepping by one, and check that a sequence can reach enough slots.
- Delete keys from an open-addressing tableExplain why emptying a slot breaks later searches, and delete correctly with tombstones or by reinserting the rest of a cluster.
- Store and find keys with linear probing
- 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 tableDecide 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 costState 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 casesExplain how an attacker can force collisions, and how universal hashing and random per-run seeds make bad inputs unlikely.
- Track the load factor and resize the table
- 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 keysDecide 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 costsApply 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 mapsRecognize 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.
- Choose and design hashable keys
Hash Tables study guide
1From 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, is the number of stored keys.
| Storage | Find | Insert or delete |
|---|---|---|
| Unsorted list | Worst-case | A set must search to prevent duplicates; finding a deletion target is linear |
| Sorted array | Worst-case | Worst-case because entries shift |
| Direct-access array | Worst-case | Worst-case |
Binary search is already optimal among methods that learn about keys only by comparing them: distinguishing among keys needs 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 , the entry for key goes directly at index . 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 , even if only three rooms are booked. For ten-letter lowercase words, the possible-key universe has 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 slots, usually proportional to the number of stored keys. A hash function sends a key into the range 0 through . 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 indices, often with . 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 . Consider keys 10, 20, 30, 40, and 50.
| Table size | Indices in insertion order |
|---|---|
| 7 | 3, 6, 2, 5, 1 |
| 10 | 0, 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 , taking a remainder selects only the lowest 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 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 . For character codes , it computes:
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:
- Read "c": .
- Read "a": .
- Read "t": .
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, and . 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 . 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 reads its characters and costs . 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.
2Separate 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 . Append each new entry at the end of its chain. Inserting 50, 700, 76, 85, 92, 73, and 101 produces:
| Bucket | Keys, in chain order |
|---|---|
| 0 | 700 |
| 1 | 50, 85, 92 |
| 2 | empty |
| 3 | 73, 101 |
| 4 | empty |
| 5 | empty |
| 6 | 76 |
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 : 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 . A successful search makes about 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 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
Nonefrom an absent key.
3Searching 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 visits , starting at . 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 , and insert 22, 1, 13, 11, 24, and 33.
| Key | Home | Slots examined | Final slot |
|---|---|---|---|
| 22 | 0 | 0 | 0 |
| 1 | 1 | 1 | 1 |
| 13 | 2 | 2 | 2 |
| 11 | 0 | 0, 1, 2, 3 | 3 |
| 24 | 2 | 2, 3, 4 | 4 |
| 33 | 0 | 0, 1, 2, 3, 4, 5 | 5 |
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, and . 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 :
| Method | Slot visited | Main tradeoff |
|---|---|---|
| Linear | Nearby memory accesses; primary clustering | |
| Quadratic | Breaks consecutive runs; may miss slots | |
| Double hashing | Key-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 . 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 , the first 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 , take and . 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 . 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 state | Find | Insert or update |
|---|---|---|
| Live entry | Compare keys | Update if equal; otherwise continue |
| Tombstone | Continue | Remember the first reusable position; continue checking |
| Empty | Report absence | Store 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:
- Key 11, home 0, moves into slot 2.
- Key 24, home 2, lands in slot 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.
4Controlling 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 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:
| Key | Old remainder | New remainder |
|---|---|---|
| 6 | 6 | 6 |
| 14 | 6 | 14 |
| 30 | 6 | 14 |
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 entries costs expected with suitable hashing; severe collisions can make repeated insertion cost . 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:
old entries. Each term is twice the previous one. The geometric sum bounds the total movement by fewer than entries for 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
| Bound | What it describes |
|---|---|
| Worst-case | A limit that applies to every allowed input and operation |
| Expected | An average over randomness in the hash function or an explicit model of the keys |
| Amortized | Total 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 : 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 add up to 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 . 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:
These are expectations, not exact predictions for one particular search.
| Load | Hit probes | Miss or insertion probes |
|---|---|---|
| 0.5 | 1.5 | 2.5 |
| 0.75 | 2.5 | 8.5 |
| 0.9 | 5.5 | 50.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 , 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 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 keys and only slots, at least one slot receives at least 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 is universal when every fixed pair of distinct keys has collision probability at most over a uniformly random choice of function:
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 larger than the keys and at least the table size. Choose from 1 through and from 0 through , then use:
The first remainder mixes the key in the larger prime range; the second compresses that result into the table.
For and , choose . Key 5 gives , then index 2. Key 11 gives , then index 3. A different choice, , gives indices 4 and 0. Across all 272 choices of the two parameters, this pair collides 32 times: about 0.118, below .
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 . The key itself contributes one entry; each other fixed key contributes collision probability at most . 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.
5Choosing 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
| Value | Can it be a key? |
|---|---|
| Integer, float, string, or bytes | Yes |
| Tuple | Yes, if every element is hashable |
| Frozen set | Yes; its elements are hashable |
| List, dictionary, or set | No |
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
equalsandhashCodeto 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
| Expression | Result or effect |
|---|---|
x in s, s.add(x), s.discard(x) | Test, add, or remove set membership; discard tolerates absence |
k in d | Test 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 time with suitable keys and 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 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 | bgives{1, 2, 3, 4, 5}: union.a & bgives{3, 4}: intersection.a - bgives{1, 2}: difference.a ^ bgives{1, 2, 5}: symmetric difference.
On average, intersection takes time by iterating the smaller set and checking the larger. Union takes .
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.
getleaves a missing key absent, whilesetdefaultcan insert it.Countercounts 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 , sorting each signature costs ; 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
1Compute where a key belongs
12 steps
- 1IntroductionStart 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.
- 2ExampleGive 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.
- 3ConnectionCompress 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.
- 4ChallengeChoose 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.
- 5ExplanationSeparate the code from the index
A hash code is an integer; the table compresses it to a valid index, for example with . 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.
- 6ExampleSee 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.
- 7ChallengeCheck 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.
- 8ExplanationRead a string from left to right
A polynomial string hash gives character positions different weights. Horner’s rule starts with zero and updates for each character code .
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.
- 9ExampleRead 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 . After "a", compute , then reduce to . The value 35 now carries the weighted contribution of the first two characters into the next update.
- 10ExampleFinish the string hash
For the final "t", use the previous reduced value 35: , and .
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.
- 11ChallengePreserve the identity of a pair
A key’s equality uses both
nameandyear, 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. - 12RecapConnect 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.
2Build and use a chained map
11 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionKeep colliding keys together
- 2ExamplePlace the first four keys
- 3ExampleFinish the chains
- 4ExampleCount hits and misses
- 5ChallengeUpdate and remove
- 6TipCreate genuinely separate buckets
- 7ExplanationCount new keys, not assignments
- 8ExampleRemove one pair safely
- 9ChallengeCheck a short operation sequence
- 10ChallengePreserve the bucket invariant during growth
- 11RecapKeep storage and behavior aligned
3Follow probe paths and repair deletion
17 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionA collision becomes a path
- 2ExampleFill the home slots
- 3ExampleGrow one consecutive run
- 4ExplanationUse an empty slot as evidence
- 5ChallengeWrap a new insertion
- 6ExampleUse square offsets instead
- 7Key InsightCheck which slots are reachable
- 8ExampleLet a second hash choose the step
- 9ChallengeDiagnose a short cycle
- 10ExampleCreate a hole and lose a key
- 11ExplanationKeep a deleted marker
- 12TipDelay reuse until absence is known
- 13ChallengeUpdate beyond a tombstone
- 14ExampleRepair a linear cluster instead
- 15ConnectionMatch the repair to the path
- 16ChallengeConnect occupancy to a rebuild
- 17RecapPreserve the search invariant
4Explain why a table stays fast
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionTrack two kinds of work
- 2ExampleCross the growth threshold
- 3ExampleRecompute placement during growth
- 4ExampleAdd the rebuild sizes
- 5ChallengePrevent repeated shrinking and growth
- 6ExplanationRead both qualifications
- 7ExampleCompare high-load misses
- 8ChallengeIdentify an expensive operation
- 9ExplanationMove the randomness into the table
- 10ExampleEvaluate a randomly chosen function
- 11Key InsightCount expected neighbors
- 12ChallengeKeep one stable random choice
- 13ChallengeSeparate two performance diagnoses
- 14RecapState the promise precisely
5Use the right key and remember earlier work
16 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionDecide what the program must remember
- 2ExampleInspect a nested key
- 3ExplanationMake equality and hashing agree
- 4ChallengeDistinguish identity from contents
- 5ExampleChoose missing-key behavior
- 6ConnectionOrder is separate from hashing
- 7ChallengeAvoid a value scan
- 8ExplanationKeep an invariant about earlier items
- 9ExampleProcess the first two values
- 10ExampleFind the earlier partner
- 11ChallengeTest the check-before-store rule
- 12ExampleCount before choosing the first
- 13ConnectionConstruct a shared grouping key
- 14TipMutate through a stable snapshot
- 15ChallengeChoose a structure for the whole task
- 16RecapStore exactly the information needed
Hash Tables practice questions
Set 1: Keys, collisions, and basic operations10 Practice Questions
Question 1 of 10
{"cedar": 4}. What is its size after assigning d["cedar"] = 9?Show answerHide answer
Question 2 of 10
-9 % 5 to?Show answerHide answer
Question 3 of 10
Show answerHide answer
Question 4 of 10
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?Show answerHide answer
Question 5 of 10
[[]] * 6?Show answerHide answer
Question 6 of 10
k % 7. Insert 6, 13, and 20 in that order. Where is 20 stored?Show answerHide answer
Question 7 of 10
Show answerHide answer
Question 8 of 10
Show answerHide answer
Question 9 of 10
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?Show answerHide answer
code.Question 10 of 10
value = d.get("oak", 0). What are value and d afterward?Show answerHide answer
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
k % 9, how many probes does finding missing key 35 take?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
d = {"elm": 2, "pine": 5}, execute d["elm"] = 8, then delete "pine" and assign d["pine"] = 6. What does list(d) return?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
[3, 7, 8] and target 14, what false result can it report?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
hash(("cell", [4, 6])) raise TypeError?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
(2, "a") and (6, "b") in four buckets. After updating key 2 and removing key 6, what should its size be?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
k % 8. All later slots remain empty. How many probes does a lookup for missing key 16 require?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
k % 7. Delete 5 using cluster reinsertion. In which slots do 12 and 19 end up?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
(name, year) for equality but hashes only name. A workload has many years for each of a few names. What diagnosis and change fit?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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?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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
k % 10. It then updates key 19. Which slots are examined during that update?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
hash(word) values from one Python run and uses them to identify words in another. Why is this unreliable even for ordinary strings?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
{2: "first", 2.0: "second"} contain in Python?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
a = {2, 4, 6} and b = {4, 7}, what does a ^ b produce?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
"".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?Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Abstract data type
Aliasing
Amortized cost
B
Balanced search tree
Bucket
C
Canonical key
Capacity
Chain
Cluster reinsertion
Collision
Complement
Compound key
Coprime integers
Counter
collections module that records how often hashable items appear.D
Default dictionary
defaultdict(list) lets grouping code append an item without first creating the group’s list.Direct-access array
Division method
Double hashing
E
Equality–hash contract
Expected cost
F
Frequency map
Frozen dataclass
dataclass(frozen=True).G
Geometric growth
H
Hash caching
Hash code
Hash flooding
Hash function
Hash seed
Hashability
Home slot
Horner’s rule
I
Identity-based equality
Immutability
Insertion order
Intersection
a & b identifies IDs shared by two collections without preserving duplicates.K
Key universe
L
Lazy deletion
Linear probing
Load factor
M
Map
Map interface
m[key] and len(m) like a dictionary.Memoization
functools.cache needs hashable arguments because it uses them to identify stored results.O
Open addressing
Overwrite
P
Polynomial hash
Primary clustering
Probe
Q
Quadratic probing
R
Rehashing
Resize thrashing
S
Secondary clustering
Sentinel
object() default lets code distinguish a missing key from a key whose stored value is None.Separate chaining
Set
Set difference
a - b finds IDs in a that are missing from b; reversing it asks a different question.Shrink threshold
Symmetric difference
a ^ b combines the two one-sided differences while removing every shared ID.T
Table index
hash(key) % 7 produce an index from zero through six.Tombstone
U
Uniform hashing assumption
Union
a | b keeps shared IDs as single elements in the result.Universal hash family
V
Visited set
W
Worst-case cost
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.