~/learn/Python · Algorithms for interviews

Hash maps and counting

The single most useful interview pattern.

9 min readlesson 16 of 23dictcounterhash map

why this matters

Counting things and looking them up instantly is the backbone of most coding-round answers — and it turns O(n²) solutions into O(n).

Dicts and sets look up in roughly constant time, which turns many quadratic solutions into linear ones. The trick is usually 'what have I already seen?'.

python · editable
loading editor…

Try it: Return the values instead of the indices.

collections.Counter counts anything iterable and ranks it, replacing a manual loop.

python · editable
loading editor…

defaultdict groups items without writing the 'if key not in dict' dance.

python · editable
loading editor…

Why dicts win

list lookup  → check every item   (slow)
dict lookup  → jump straight there (instant)

Pro tip

Counter(items).most_common(3) does grouping, counting and sorting in one line.

Common gotcha

Only immutable things (strings, numbers, tuples) can be dict keys. A list as a key raises TypeError: unhashable.

key takeaways

  • Dict lookups are near-instant regardless of size.
  • Counter counts occurrences in one call.
  • Keys must be immutable.

check your understanding

Which finds the 2 most common words fastest?

free practice

Build confidence with a question you can solve without Pro.