FMTechnical notesPortfolio
Back to the blog

Computer Science · Intermediate

Hash tables: fast lookups and collisions

A hash table transforms a key into a position. With good distribution, insertion and lookup are O(1) on average.

After reading this
  • Understand a hash function
  • Visualize collisions
  • Separate average from worst case
01 / 03

From text to index

The hash function must be deterministic and distribute keys. Modulo fits the result into the bucket count.

js
function hash(key, size) {
  let total = 0;
  for (const char of key) total += char.charCodeAt(0);
  return total % size;
}
02 / 03

Two keys, one bucket

A collision is not an error; it is part of the design. Separate chaining stores a small collection per bucket; open addressing finds another position.

  • More buckets reduce collisions and consume more memory.
  • A poor function concentrates keys.
  • Load factor tells you when to resize.
03 / 03

In products: use Map

Implementing a table teaches the concept. In JavaScript applications, Map already handles identity, growth, and collisions robustly.

Hash-table lab● interactive
BUCKET_0
BUCKET_1
BUCKET_2
node
BUCKET_3
react
next
react
Practice

Create a collision

With four buckets, find two words that end up at the same index using the example function.

Show a hint

Reorder letters: the simple sum has obvious limitations.