Hashing — The Complete Guide
Master hashing from first principles. Learn to recognize when a hash map is the right tool, build strong intuition for frequency counting and complement lookups, and confidently solve interview questions.
Intuition from Scratch
Why does this pattern exist?
The fundamental problem hashing solves is search. Given a collection of data, how do you check if something exists — or find its associated value — without scanning everything? Arrays give you O(n) search. Sorted arrays give you O(log n) with binary search. But a hash map gives you O(1). Constant time. Regardless of whether you have 10 items or 10 million.
A hash function takes your key (a number, string, or any data) and converts it into an index in an array. That index is where the value lives. When you want to look it up later, you hash the key again, jump straight to that index, and grab the value. No scanning, no comparing — just one jump.
In coding interviews, hashing is the single most versatile pattern. It's the tool you reach for when you need to trade space for time — store something now so you can look it up instantly later. Two Sum, Group Anagrams, finding duplicates, frequency counting — all of these are hashing problems at their core.
Analogies to Build Intuition
The Book Index
A book's index maps topics to page numbers. You don't read every page to find 'recursion' — you look it up in the index, get page 42, and flip straight there. A hash map is the same: it maps keys to values so you can jump directly to what you need.
The Filing Cabinet
Imagine a filing cabinet where each drawer is labeled A-Z. To file a document for 'Smith', you go straight to the 'S' drawer. To retrieve it, you go to 'S' again. You never search every drawer. The label is the hash — it tells you exactly where to look.
The Coat Check
At a coat check, you hand over your coat and get a numbered ticket. When you come back, you give the ticket and get your coat instantly — the attendant doesn't search through all coats. The ticket number is the hash, and the coat rack is the hash table.
What kind of problems does it solve?
Hashing is your go-to when:
- You need O(1) lookup — "have I seen this before?"
- You need to count frequencies of elements
- You need to find a complement or pair — "does target - current exist?"
- You need to group items by some key (anagrams, patterns)
- You need to preserve original indices while searching
- You want to reduce O(n²) brute force to O(n) by trading space for time
The core insight
Hashing trades space for time. By storing data in a hash map, you convert O(n) searches into O(1) lookups. The cost is O(n) extra space — but in almost every interview problem, that trade is worth it. When you see a nested loop where the inner loop is "searching for something," hashing can almost always eliminate it.