← Hashing · guided lesson
Hashing & Prefix Sums
the story
Hash table
Every tool here exists because something was too slow or broke without it. Here is what.
In January 1953 Hans Peter Luhn wrote an internal IBM memo that put keys into numbered buckets and chained the overflow — one of the first uses of linked lists. At about the same time, Gene Amdahl, Elaine McGraw (née Boehme), Nathaniel Rochester and Arthur Samuel used hashing in an assembler for the IBM 701; Amdahl is credited with open addressing with linear probing. Arnold Dumey gave the first published description in 1956, and W. Wesley Peterson's 1957 paper studied open addressing in depth. Knuth's The Art of Computer Programming, Vol. 3 (§6.4), tells the full story.
the problem it solved
Finding a record by its key in about one step, instead of scanning everything or keeping the data sorted.
why it matters: without it
Every "have I seen this?" or "what's stored under this key?" would cost O(n), or O(log n) with sorted structures — caches, compilers and deduplication would all slow down by orders of magnitude.
sources: IEEE Spectrum — Hans Peter Luhn and the Birth of the Hashing Algorithm (2018) ↗ · Peterson — Addressing for Random-Access Storage (IBM J. Res. Dev., 1957) ↗ · Knuth — The Art of Computer Programming, Vol. 3, §6.4 Hashing (history) ↗ · Wikipedia — Hash table: History (Luhn's memo, the IBM 701 assembler, Dumey, Peterson) ↗ · Pro Git — Git Internals: Git Objects (objects stored by hash under .git/objects) ↗
also in this chapter: Java's HashMap (resize + treeify) · Prefix sums (1D) · 2D prefix sums (summed-area table) · Prefix sum + HashMap
the idea
The idea in 30 seconds
A hash function turns a key into an array index, so finding a key is one jump instead of a scan: O(1) on average.
A prefix sum array stores running totals once, so the sum of any range is prefix[r+1] − prefix[l]: O(1) per question.
Together they solve "count subarrays with sum k" in one pass: remember every prefix sum you've seen in a HashMap.
picture this
Hashing is how Git stores your files: it hashes each object's content, and the first two hex digits of that hash pick one of 256 folders under .git/objects/. Finding an object is one jump into one small folder, never a search through all of them. A prefix sum is a cricket scorecard's running total: runs scored between over 10 and over 20 = total after 20 − total after 10.
watch it
HashMap.put in 3D: hash, bucket, chain
Predict mode is on. Before each step, guess what happens, then watch. Wrong guesses are fine; that is how it sinks in.
HashMap.put in 3D: hash, bucket, chain
Each key is hashed to a bucket. Collisions chain up; equal keys overwrite instead of duplicating.
On this screen ← / → step the simulation. Use the buttons below to move through the lesson.
watch it
Load factor 0.75: resize and rehash
Predict mode is on. Before each step, guess what happens, then watch. Wrong guesses are fine; that is how it sinks in.
Load factor 0.75: resize and rehash
Start small and watch the table double. Every entry moves, because its bucket depends on the capacity.
On this screen ← / → step the simulation. Use the buttons below to move through the lesson.
key idea 1 of 9
Read it once. Say it out loud once. Bas.
Hash → bucket: index = hash(key) mod capacity. Different keys can land in the same bucket (a collision); Java keeps them in a chain (separate chaining) and tells them apart with equals.
key idea 2 of 9
Read it once. Say it out loud once. Bas.
Load factor 0.75: when size > 0.75 × capacity, HashMap doubles its table and re-hashes every entry. One resize is O(n), but they're rare, so put is O(1) amortized.
key idea 3 of 9
Read it once. Say it out loud once. Bas.
Java 8+ treeification: if one bucket grows past 8 entries and the table has at least 64 buckets, that chain becomes a red-black tree, so even a bad bucket costs O(log n), not O(n). With a smaller table, Java resizes instead.
key idea 4 of 9
Read it once. Say it out loud once. Bas.
equals/hashCode contract: equal objects must have equal hash codes. Override both or neither, and never mutate a key while it's inside a map.
key idea 5 of 9
Read it once. Say it out loud once. Bas.
Pick the flavour: HashMap/HashSet = fastest, no order · LinkedHashMap = insertion (or access) order · TreeMap/TreeSet = sorted, O(log n), floor/ceiling queries.
key idea 6 of 9
Read it once. Say it out loud once. Bas.
Counting is the #1 hashing pattern: map.merge(x, 1, Integer::sum). If keys are small integers or letters, an int[] is a faster "perfect" hash table.
key idea 7 of 9
Read it once. Say it out loud once. Bas.
One-to-one mappings need two maps: "each letter stands for one word and no two letters share a word" is two rules, so check both directions.
key idea 8 of 9
Read it once. Say it out loud once. Bas.
Prefix sums: prefix[i+1] = prefix[i] + nums[i] with prefix[0] = 0. The leading zero removes the "range starts at 0" special case.
key idea 9 of 9
Read it once. Say it out loud once. Bas.
Prefix sum + HashMap: a subarray (j..i] sums to k exactly when prefix[i] − prefix[j] = k. So at each i, ask the map how many earlier prefixes equal prefix[i] − k. This works with negative numbers, where sliding window fails.
spot the pattern
When you see this, think this
"Find a pair / complement" in an unsorted array, return indices
HashMap value → index, look up
target − xbefore storing x"Duplicate", "seen before", "unique", "first repeating"
HashSet (
addreturns false on repeats)"Frequency", "most common", "anagram", "top k"
Counting map or int[26]; then bucket sort or a heap
"Can you build X from the letters of Y?"
Count Y's letters, then spend them on X (int[26])
+7 more signals on the chapter page
watch out
A trap or two
Many wrong answers in interviews come from small slips like these, not from the hard part.
- Forgetting
seen.put(0, 1)(orprefix[0] = 0). Subarrays that start at index 0 are silently missed. - Storing into the map before looking up. In Two Sum,
[3]with target 6 would pair 3 with itself.
quick check
One question. No pressure.
A HashMap has capacity 16 and the default load factor. On which put does it resize?
now try
Your first real problem
You know enough to try this one. Stuck? Use the hints; that is what they are for.
Two Sum
open the problem →recall
Flip a few cards
Answer in your head first, then flip. Grade yourself honestly; the schedule brings back what you forget.
HashMap get/put in Java 8+: average and worst-case cost?
Question 1: HashMap get/put in Java 8+: average and worst-case cost?
done
Lesson complete
Chalo, that is the core. The full chapter has the rest: cost tables, Java details and more problems.