Skip to content

Arrays & Hashing

Arrays & Hashing in under a minute

The most common pattern in interviews. A hash map or set gives O(1) lookups, which usually turns an O(n²) “compare everything with everything” loop into a single pass.

  • You need to know “have I seen this before?” or “how many times?”
  • The brute force is a nested loop looking for a matching partner.
  • You need to group items that share some property (same letters, same remainder).
  • Order doesn’t matter, or the input is unsorted and you can’t afford to sort.
  • The problem asks for O(n) time and says nothing about O(1) space.
seen = {} # or set(), or collections.Counter()
for i, item in enumerate(items):
key = make_key(item) # the property that defines "a match"
if key in seen: # 1. ask about the past
use(seen[key], i)
seen[key] = i # 2. record the present

The whole skill is choosing the key: the complement (target - num), the sorted letters of a word, a running prefix sum.