Courses / Computer Science I
Data Structures

Hashing and Dictionaries

Computer Science I 225 words Free to read

Finding Things Instantly

A dictionary (map) ADT stores key–value pairs for fast lookup, insertion, and deletion by key. The underlying structure is the hash table.

A hash function computes an integer from a key. Reduced modulo the array size, this gives the index of the bucket holding that value:

index=hash(key)modm\text{index} = \text{hash(key)} \bmod m

When keys spread evenly, operations take O(1)O(1) on average. Because two different keys can yield the same index, collisions occur. Every hash table uses a collision-resolution strategy to prevent overwriting values.

StrategyMechanism
ChainingStores a small list at each bucket for all matching keys
Open addressingProbes to a different empty bucket by a fixed rule

Performance and Pitfalls

Performance relies on the load factor (elements divided by buckets). As the table fills, collisions increase. To maintain speed, hash tables resize by allocating a larger array and rehashing all elements.

Common Pitfall: Believing hash lookups are guaranteed O(1)O(1). The O(1)O(1) is an average under a good hash function and low load factor.
CaseComplexityCondition
Average caseO(1)O(1)Good hash function, reasonable load factor
Worst caseO(n)O(n)Many keys colliding into a single bucket
Hashing and Dictionaries

Practise this lesson

The explanation above is free to read. The graded practice for this lesson lives in the Tryals app.

10practice questions
2interactive scenes

Data Structures