DSA Trainer
← All patterns
Pattern

Hash Map Pattern

Stop scanning backward. Store what you've seen and look it up in one step.

Quick Summary

Best used when

  • You need to find the complement or pair of a current value
  • You need to look up something you saw earlier in the input
  • You need to store counts, indexes, or relationships alongside each key
  • You want to eliminate a nested loop that scans the array repeatedly

Clue words in the problem

two sumcomplementcount occurrencesindex ofgroup bypair

Complexity gain

O(n²) nested loops → O(n) single pass

Why this pattern matters for LeetCode

Hash Map problems disguise themselves as array problems. The real ask is: look up something from earlier in the input. Without a hash map, you write nested loops — for each element, scan everything before it. That is O(n²) and times out on large inputs. The hash map fixes this by letting you store what you have seen and look it up in constant time. You pay a little extra space to avoid a lot of wasted time.

What the Hash Map pattern is

A hash map stores key-value pairs and retrieves any value by key in O(1) average time. The core idea is simple: instead of scanning the array every time you need to find something, store what you've already seen so you can check it instantly. In the Two Sum pattern, you store each number and its index as you go. When you see a new number, you check whether its complement is already in the map before adding the current number. One pass, done.

Reach for Hash Map when you catch yourself thinking…

These are the internal questions that signal this pattern.

Do I need to find the complement or pair of the current value?
Would a nested loop work but feel too slow?
Do I need to look something up that I saw earlier in the array?
Am I checking if something exists while also storing data about it?

Beginner mental model

A hash map is like a notebook with an index. When you read page 42, you jot 'page 42 → dinosaurs' in the index. Next time someone asks about dinosaurs, you check the index — instant answer, no re-reading the book. In Two Sum: as you walk through the array, you write each number and its position into the notebook. When you encounter a new number, you check the notebook for its complement before writing the new entry down.

Ready to practice Hash Map?

DSA Trainer gives you guided hints, not answers, so you build real intuition.

When to use Hash Map

  • Finding pairs or complements in an unsorted array (Two Sum style)
  • Counting how often each value appears
  • Grouping elements by a shared property (Group Anagrams)
  • Looking up whether you have seen something before, and retrieving data about it
  • Replacing an O(n) inner loop with a single O(1) lookup

When NOT to use Hash Map

  • You only need to check existence, not store any extra data — a Set is simpler
  • You only need to count occurrences — a plain object or Frequency Map is more readable
  • The input is already sorted and you need pairs — Two Pointers may be O(1) space instead
  • The key space is a small integer range — an array can act as a direct-address table

Better alternative: In those cases, a Set, Frequency Map, or Two Pointers may be simpler and use less space.

JavaScript code template

Two Sum core pattern — O(n) time, O(n) space

const map = new Map();

for (let i = 0; i < nums.length; i++) {
  const complement = target - nums[i];

  if (map.has(complement)) {
    return [map.get(complement), i];
  }

  // Check FIRST, then store — avoids matching an element with itself
  map.set(nums[i], i);
}

return [];

For each number, compute what value would pair with it to reach the target. Check the map for that complement first. If it's there, you're done. If not, store the current number so a future element can find it. The 'check before store' order is critical — it prevents a single element from matching itself.

Step-by-step thinking process

Walk through this in your head before writing code.

  1. 1Identify what you want to store as the key (the number itself) and the value (its index).
  2. 2Start the loop. For each element, figure out what you'd need to have already seen.
  3. 3Check the map for that needed value before doing anything else.
  4. 4If found, you have your answer — return or record it.
  5. 5If not found, store the current element in the map so future iterations can find it.
  6. 6Continue until the loop ends or the answer is found.

LeetCode-style problems that use this pattern

Practice on DSA Trainer with guided hints: no spoilers, just nudges.

Coming soon

  • Subarray Sum Equals K

    Store prefix sums in a map and check for the target difference at each step.

    Coming soon

Common mistakes beginners make

  • Storing the value before checking — this makes an element match itself, which is the classic Two Sum off-by-one bug.
  • Using a plain object {} when keys could be non-strings or negative numbers. Use Map() for safety.
  • Reaching for a Set when you need to store extra data per key (like an index or count) — Set only stores existence.
  • Writing a nested loop instead — if you're scanning the whole array for each element, you've missed the hash map optimization.
  • Forgetting that Map.get() can return undefined — always handle the case where the key doesn't exist before using the value.

Hash Map vs Set vs Frequency Map

Choose the right tool for the job.

PatternUse when…
Hash MapYou need to store and retrieve a value (index, count, object) alongside each key
SetYou only need to know whether something has been seen before — no extra data needed
Frequency MapYou need to count how many times each value appears and compare those counts

Time and space complexity

Time complexity

O(n)

Space complexity

O(n)

You visit each element once (O(n)) and each map lookup or insert is O(1) average. You store at most n entries in the map, so space is O(n). In the rare worst case where every key hashes to the same bucket, lookup degrades to O(n) — but this doesn't happen with standard inputs.

Ready to practice Hash Map?

DSA Trainer gives you guided hints, not answers, so you build real intuition.

Frequently asked questions

How do I know when to reach for a hash map?
Ask: 'Do I need to look up something I've already seen, while also storing data about it?' If yes, use a hash map. If you only need to check existence (not retrieve data), a Set is enough. If you only need counts, a plain object works fine.
Why does Two Sum use a hash map instead of sorting and using two pointers?
Both work, but they have different tradeoffs. Sorting + two pointers is O(n log n) time and O(1) extra space but destroys the original indexes. Hash map is O(n) time and O(n) space and preserves indexes. Since Two Sum asks for indexes, the hash map approach is cleaner and faster.
What's the difference between a hash map and a Set?
A Set only stores keys — it tells you 'have I seen this value before?' A Map stores key-value pairs — it tells you 'have I seen this value, and what data did I record about it?' Use a Map when you need to retrieve something (an index, a count, an object) alongside the key.
Is hash map lookup really O(1)?
On average, yes. A hash function converts the key to an array index in constant time, and the lookup is one array access. In the worst case (all keys collide to the same bucket), it degrades to O(n). For LeetCode problems, assume O(1) average — it's the intended complexity.

Explore other patterns