Python/Algorithms for interviews 9 min

Hash maps and counting

The single most useful interview pattern.

dictcounterhash map

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…