Pattern

Hash map

Trade an O(n) or O(n²) scan for O(1) average lookups by keying a map on the exact fact you need to check.

What it is

A hash map turns "have I seen this before, and what did I learn when I did" into a single O(1) average lookup instead of a re-scan. What goes in the map varies by problem: a value's index, a running prefix sum's occurrence count, a canonical form of a string, or a linked structure's original-to-copy mapping. The data itself can be an array, string, or graph — the map is the accelerator sitting alongside it, not the primary structure, except in problems where the map (plus a companion list) is the whole design, such as a cache.

When it applies

Tells in the problem

The classic mistake

The recurring bug is checking membership after inserting the current element instead of before, or inserting into a count map without a starting seed that represents "nothing consumed yet." Both look like off-by-one errors: a two-sum implementation that matches an element with itself, or a prefix-sum counter that silently drops every subarray beginning at index 0 because the map never held a zero-sum baseline. It happens because the map update and the map lookup feel like one step when you're moving fast, and the order between them is exactly what makes the difference between correct and subtly wrong. Catch it by tracing the smallest possible input by hand — a two-element array, or a single element equal to the target — before trusting the loop on larger cases.

Questions to start with

All 26 hash map questions

Problem statement, examples and hints are free on every page; the worked approach, solution and tests are in the company guides.

Free starter pack

13 must-tier questions with full solutions

Sign in with an email — no purchase — and read them in the full reader.

No password, no spam. One sign-in email; you can read the pack in the full reader.