Pattern · Interview prep
Hash Map
Store a value under a key so a later question — have I seen this, or which index held it — is one lookup.
What it is
What is the hash map pattern?
A hash map keeps a payload under a key. The next step can ask whether that key was seen, or which index went with it, without scanning the earlier items again. You spend memory so each lookup stays expected constant time.
- Complement. Store each value with the index that held it. The next value asks for target minus itself.
- Frequency. Count how often each key appears. A later pass reads that count instead of scanning the whole input again.
7 needs 2, and 2 is already stored at index 0
When to use it
How do you recognize a hash map problem?
Read the statement for these signals before you nest a second loop.
Read the full recognition guide: Hash map or sorting? How to choose
Phrases to watch for
- pair that sums to
- the list is not sorted
- frequency
- first unique
- group by
- complement
- seen before
- 1
You need the partner of the current value
The partner is determined by the value you are holding, such as target minus this number.
- 2
You are counting or grouping
The question is how often a key appears, or which items share the same key.
- 3
A nested scan would repeat the same lookup
Each earlier item answers the same yes-or-no question. Remember the answer instead of searching again.
Looks similar, but isn’t
The row is already sorted
A sorted pair can move two ends inward. That is Two Pointers, and it does not need a map.
The answer is a moving slice
If you grow and shrink a contiguous stretch, start with Sliding Window. A map may track what is inside that slice, but the slice is the pattern.
You only need membership
When the index does not matter, a Hash Set stores the value and nothing else.
Worked example
How does it work on an unsorted pair that sums to a target?
Exactly one pair of different positions adds up to the target. Return those indexes, smaller first. The list is not sorted, and one position cannot be used twice. This is the classic complement lookup, and one of the problems you can practice below.
function indexOfPair(nums: number[], target: number): [number, number] | null { const seen = new Map<number, number>(); for (let index = 0; index < nums.length; index += 1) { const value = nums[index]; const need = target - value; // Look up before storing, so this index cannot match itself. const partner = seen.get(need); if (partner !== undefined) return [partner, index]; seen.set(value, index); } return null;}Look up the partner before storing the current index.
Code is shown in TypeScript. You can solve problems in TypeScript, JavaScript, or Python.
Complexity
- TimeO(n)
Each index is visited once. A map lookup and a map write are expected constant time.
- SpaceO(n)
The map holds one entry per value seen so far, which can be the whole row.
Why the map stores an index
The answer is positions, not values. The key is the number you saw. The payload is where it sat.
A count, then a second pass
For the first character that appears once, count every character, then walk the original string and return the first character whose count is 1. The map does not remember order.
Step by step on [2, 7, 11, 15] with target 9
- 1
At index 0 the value is
2. It needs7, and the map is empty, so store2under index0.2L·R71115 - 2
At index 1 the value is
7. It needs2, and the map returns index0. Return[0, 1]. Storing7first would let a value match itself.271115
Common mistakes
What mistakes do people make with hash map?
Storing the value before the lookup
If the current value is inserted first, it can be found as its own partner. A single position is then used twice.
InsteadAsk for the complement first. Store the current index only after that lookup misses.
Saving the value when the answer is the index
A map from value to value tells you the number existed. It does not tell you where.
InsteadStore the index. When the complement hits, return that stored index and the current one.
Trusting the map to remember order
Keys are not in the order they arrived. The first unique character is not the first key you happen to read back.
InsteadCount with the map, then walk the original string for the first character whose count is 1.
Matching a repeated value with one index
Two equal numbers are a legal pair when they sit at different positions. Overwriting the only stored index loses the earlier one if you still need it.
InsteadLook up before you overwrite. For a pair, the earlier index is the partner. For a count, add one instead of replacing the entry.
Practice it in Algofily
Which Algofily problems train hash map?
8 problems are tagged Hash Map. They run from an unsorted pair and a first unique letter to a covering window.
- Pair With TargeteasyHash MapA list of integers and a target sum are on your desk.Algofily 40Open problem
- Locked: opens after you create an account. First Unique LettereasyHash MapReturn the first character in a message that appears exactly once.Algofily 40Open problem
- Locked: opens after you create an account. Matching Stock LabelseasyHash MapTwo warehouse labels match when they contain the same characters with the same frequencies, in any order.Algofily 40Open problem
- Locked: opens after you create an account. Longest Distinct StretchmediumSliding Window · Hash MapA log line is a string.Algofily 40Open problem
- Locked: opens after you create an account. Most Common ValueeasyHash MapA checkout log lists product ids, one per scan.Algofily 40Open problem
- Locked: opens after you create an account. Anagram ClustersmediumHash MapGroup words that use the same letters with the same frequencies.Algofily 40Open problem
- Locked: opens after you create an account. Shortest Covering WindowhardSliding Window · Hash MapFind the shortest contiguous slice of text that contains every character in need, including duplicates.Algofily 40Open problem
- Locked: opens after you create an account. Top Frequent ValuesmediumHeap · Hash MapReturn the k values that appear most often.Open problem
A lock means the problem opens after you create an account. Pair With Target is open to try without one.
Start Learning.
Work Pair With Target through all seven stages. An account saves that progress and opens every other problem.