CodeSpeek

When the answer is a hash map

If a brute force is two nested loops and the inner one is only searching, you are usually one hash map away from linear.

The signal

Ask: is the inner loop looking something up? Two-sum's inner loop asks "is target minus n here?". Contains-duplicate's asks "have I seen this?". Group-anagrams asks "have I seen this shape?". Every one of them is a lookup, and a lookup is what a hash map makes constant.

What to store

The interesting choice is not "use a map" — it is what the key is.

Set or map?

A set if you only need membership, a map if you need something back. Say which and why — "a set, I only need to know whether I've seen it" is a sentence that shows you chose rather than defaulted.

When it is the wrong answer

If the input is already sorted, two pointers usually beat a map and use no extra space. If you need order, or a min or max repeatedly, you want a heap or a sorted structure. And a map keyed by something unhashable — a list — needs converting to a tuple first, which is a good thing to say aloud before you type it.

The cost

O of n space, and worst-case O of n lookups on adversarial keys. In an interview, constant is the right thing to claim, but knowing why it is amortised is worth a sentence.

Practise this More guides