Courses / DSA Patterns for Working Engineers / Chapter 24
Module 8 · Hash maps, tracking, union-find and custom structures · Chapter 24 of 39
Hash Maps: Lookups, Complements and Pattern Matching
Builds on The Coding Interview: How the Round Runs and How to Prepare. Next up: Knowing What to Track: Counts, Signatures and Frequencies.
Part 1 · Introduction to hash maps
What a hash map is
A vehicle registry, a spell checker and a log filter all need the same thing: given a key, find what belongs to it without reading every record. A hash map does that in constant time on average.
A hash map (also called a dictionary or associative array) stores pairs of a key and a value. You give it a key and it returns the value, tells you the key is missing, or replaces the value. A hash set is the same idea with keys only: it answers "have I seen this?". JavaScript ships both as Map and Set.
Without a hash map you have two choices. An unsorted array makes every lookup a scan of up to n entries. A sorted array allows binary search, but every insert has to shift entries. A hash map gives up order in exchange for lookups, inserts and deletes that take a handful of steps whatever n is, as long as it is used well.
Most lessons in this part of the course are a hash map plus one idea about what to store in it, such as the amount still needed or the last time a message was printed. This lesson explains how the structure works.
Code blocks follow the convention set out in the first chapter: a block that starts a file shows its imports, other blocks may leave them out, and rng.ts holds that chapter's mulberry32.