Module 3 · Arrays, Strings and Hashing · Lesson 8 of 40
Hashing: finding things instantly
How a hash function turns a key into a bucket number, what collisions are, and why lookups are O(1) on average.
In this lesson · about 18 minutes
- Explain what a hash function does
- Explain collisions and how chaining handles them
- Say why dict and set lookups are O(1) on average
Searching a list for a word means checking items one by one: O(n). What if you could jump straight to the right spot, like you jump to nums[5]? That is the idea of hashing.
The hash function
A hash function turns a key (like the word "apple") into a number. We use that number to pick a bucket in a table: bucket = hash(key) % number_of_buckets. The same key always gives the same bucket, so to find "apple" later, you compute its bucket and look only there.
Collisions
Two different keys can land in the same bucket. That is a collision. One simple fix is chaining: each bucket holds a small list, and colliding keys line up in it. Another fix, open addressing, tries the next free bucket instead.
Load factor and resizing
The load factor is items ÷ buckets. When it gets too high, chains get long and lookups slow down. So the table resizes: it makes more buckets and moves every item to its new bucket (called rehashing). This is rare, so on average each insert is still O(1).
| Operation | Average | Worst (everything collides) |
|---|---|---|
| Insert | O(1) | O(n) |
| Look up | O(1) | O(n) |
| Delete | O(1) | O(n) |
Python's dict and set are hash tables. A good hash function spreads keys out, so in practice they behave like O(1).
Try it · see it work
Inside a hash table
Add some words. Try 'lemon', 'melon' and 'lime'. Do any collide?
Type a word, then add it or look it up.
This toy hash adds up the letter codes. Python's real hash is much better at spreading keys out, but the idea is the same: the key decides the bucket.
Try it: build a tiny hash table
This is a small version of what a dict does inside. Run it, then add your own words.
Exercise
Which bucket?
Write bucket_of(key, size) that adds up the character codes of the key (use ord(ch)) and returns that total % size.
Check your understanding0 of 3 correct
Quiz score: 0 of 3
Exercises solved: 0 of 1
Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.