Skip to content
dsa/roadmap
← All cheat sheets
05

Hashing

dsa.fetehadin.com
5.1 Hashing Basics

A hash function turns a key into an array index, so search is O(1) on average. Collisions, separate chaining, linear probing and the load factor.

search / insert / delete, averageO(1)
search / insert / delete, worst (all keys collide)O(n)
SpaceO(M + n)
  • ✗With linear probing, stopping a search at a slot holding a different key. Only an empty slot means "not found".
  • ✗Forgetting to wrap around with % M when probing.
  • ✗Claiming hashing is always O(1). The worst case is O(n).
Hash function:
Maps a key to an index of the hash table, e.g. h(k) = k mod M.
Collision:
Two different keys hashing to the same index.
Separate chaining:
Each table slot holds a list of all keys that hash there.
Linear probing:
On a collision, try the next slot (h + i) % M until an empty one.
Load factor:
α = n / M, how full a hash table is.

Keyboard shortcuts

⌘K /
Search topics, glossary, cheat sheets
space
Play / pause the visualizer
← →
Step back / forward
r
Reset the visualizer
?
Show this help