~/problems

Problems

Basics first, then the classics, then company-style assessments. Every problem has tests you run right here; multi-level ones unlock as you go. See the roadmap.

Arrays & hashing

Hash maps and counting

Counter/defaultdict, complement lookups, prefix-sum + hash map.

Notes

Recognise it when: you're counting, grouping, deduplicating, looking up a complement ("does target - x exist?"), or answering in O(1) what you've seen so far.

seen = {}
for i, x in enumerate(nums):
    if target - x in seen: return [seen[target - x], i]
    seen[x] = i

# subarrays summing to k: count prefix sums seen so far
count, prefix, seen = 0, 0, Counter({0: 1})
for x in nums:
    prefix += x
    count += seen[prefix - k]
    seen[prefix] += 1
  • Counter, defaultdict(list) for grouping. Keys must be hashable: tuple(sorted(word)) works, a list doesn't.
  • Seed with {0: 1} for prefix-sum counting, so subarrays that start at index 0 are counted.

21 problems

Interview roadmap

Arrays & hashing Counting, lookups, sorting with keys, prefix sums.

Hash maps and counting guide

esc