Inside a Dictionary: buckets and collisions

A dictionary turns the key into a number, uses that number to choose a bucket, and only searches inside that one bucket.

Time O(1) averageSpace O(n)Code C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

Hashing jumps straight to one bucket instead of scanning everything. Two keys that land in the same bucket are a collision, and they are kept in a short chain that is searched one by one.

Code

var map = new Dictionary<int, string>();
map[key] = value;
// What the indexer does inside:
//   int hash = key.GetHashCode();
//   int bucket = hash % buckets.Length;
//   walk the entries in that bucket:
//   same key found -> replace the value, otherwise add a new entry

Tips

In the .NET library

If you override Equals on a key type you must override GetHashCode too, and equal objects must return the same hash. record types do both for you.