Hash Tables
Loading
Loading
Hash Tables
What a hash table gives you, and what it charges for it.
By the end of this chapter
A hash function converts a key into an integer, which is reduced to a bucket index. Storing and retrieving both compute that index directly, so neither searches.
Concept
If several keys hash to the same bucket, they must be distinguished by scanning that bucket. With a good hash function and a reasonable load factor, buckets stay short and lookups are effectively constant. In the pathological case where everything collides, lookup degrades to O(n).
| Operation | Time | Space |
|---|---|---|
| Insert | O(1) expected | O(1) |
| Lookup | O(1) expected | O(1) |
| Delete | O(1) expected | O(1) |
| Iterate all | O(n) | O(1) |
| Any of the above, worst case | O(n) | O(1) |
| Question | Structure |
|---|---|
| Have I seen this? | Set |
| How many times have I seen this? | Map to a count |
| Where did I see this? | Map to an index |
| What goes with this? | Map to any value |
Quick quiz
Sign in to keep a note here. It is free, and nobody else can see it.
Sign inWhat this chapter was for:
Before moving on: take the quiz above.