awelgorithms

The hash map pattern: how to spot it

Updated

A hash map trades memory for time: remember what you have seen, keyed by the thing you will look up later, and a nested loop becomes one pass. Most interview problems use it for one of three jobs: finding a partner value, counting, or grouping.

When to reach for it

The usual shape

seen = {}
for i, x in enumerate(items):
    want = partner_of(x)        # e.g. target - x
    if want in seen:
        return seen[want], i
    seen[x] = i                 # store after checking, so x can't pair with itself

3 LeetCode hash maps problems, easiest first

  1. Two Sum easy

    One pass: store what you have seen, query the complement.

  2. Valid Anagram easy

    Same letters iff the two frequency maps are equal.

  3. Group Anagrams medium

    The anagram key is the grouping key. Do not overwrite the list under it.

Skills these problems use

Each one has a free lesson with worked examples and a drill.

All hash map lessons

check which skills you have 10 minutes, free, no account.

Other patterns