← All topics

Arrays & Hashing

Lists, dicts, sets, and counting patterns.

Arrays & Hashing

The bread and butter: lists for ordered data, dicts and sets for O(1) lookup.

Core syntax

  • Frequency countCounter(nums) or a defaultdict(int) with count[x] += 1.
  • Group by keydefaultdict(list) then groups[key].append(x).
  • Membershipx in seen where seen is a set (O(1), not a list).
  • Index map{v: i for i, v in enumerate(nums)}.
from collections import Counter, defaultdict
freq = Counter(nums)                 # {val: count}
groups = defaultdict(list)
for s in strs:
    groups[tuple(sorted(s))].append(s)

Watch out

  • {} is an empty dict, not a set — use set().
  • dict.get(k, default) avoids KeyError.
Full cheat sheet →