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#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

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
static void put(int key, String value) {
    Map<Integer, String> map = new HashMap<>();
    map.put(key, value);
    // What put does inside:
    //   int hash = h ^ (h >>> 16), where h = key.hashCode();
    //   int bucket = (table.length - 1) & hash;
    //   walk the entries in that bucket:
    //   same key found -> replace the value, otherwise add a new entry
}
void put(int key, const string& value) {
    unordered_map<int, string> map;
    map[key] = value;
    // What operator[] does inside:
    //   size_t hash = std::hash<int>{}(key);
    //   size_t bucket = hash % bucket_count();
    //   walk the nodes in that bucket:
    //   same key found -> return that value, otherwise insert a new node
}
table = {}
table[key] = value
# What dict does inside (CPython):
#   h = hash(key)
#   slot = h & (len(slots) - 1)
#   probe from that slot:
#   same key found -> replace the value, otherwise use the first free slot

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.