progress

~/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

Python toolkit

Counter, deque, heapq, bisect, itertools: the standard library to know cold, and its traps.

Main path: 8 problems, about 2 hours.

Notes

Know these cold. Interviewers expect you to reach for the right tool without looking it up, and to know where each one bites.

from collections import Counter, defaultdict, deque
import bisect, heapq, itertools, functools

cnt = Counter(words)        # cnt[missing] == 0
cnt.most_common(3)          # ties keep first-seen order
Counter("aab") - Counter("ab")  # {'a': 1}: counts <= 0 dropped
groups = defaultdict(list)  # groups[key].append(x)
q = deque(maxlen=k)         # O(1) at both ends
q.appendleft(x); q.popleft(); q.rotate(1)

heapq.heapify(h)            # in place, returns None
heapq.heappush(h, (prio, seq, item))  # seq breaks ties
heapq.nlargest(k, xs, key=len)
bisect.bisect_left(a, x)    # first index with a[i] >= x
bisect.bisect_right(a, x)   # first index with a[i] > x
bisect.insort(a, x)         # keeps a sorted, O(n) insert

rows.sort(key=lambda r: (-r[1], r[0]))  # stable, several keys
itertools.accumulate(xs, initial=0)     # prefix sums
itertools.combinations(xs, 2)           # also permutations,
itertools.product(xs, repeat=2)         #   pairwise, groupby

@functools.cache            # memoise; args must be hashable
def f(i, j): ...

Gotchas

  • heapq is a min-heap by default. The site runs Python 3.14, which adds heapify_max, heappush_max and heappop_max (and _max versions of pushpop and replace). Interviewers' machines may be older, so also know the classic trick: push -x. heappop on a list you never heapified returns h[0], which may not be the minimum. heapreplace pops then pushes; heappushpop pushes then pops, so a small new item comes straight back.
  • [[0] * 3] * 3 is three references to one row: use [[0] * 3 for _ in range(3)]. b = a shares a list, a[:] copies it (shallowly).
  • s[:-k] with k = 0 is '', because -0 == 0. s[::-1] reverses. Slices copy, so a slice in a loop costs O(n) each time.
  • -7 // 2 == -4 and -7 % 2 == 1: Python rounds down, C++ and Java truncate. Ceiling division is -(-a // b).
  • "a b".split() is ['a', 'b'], but split(" ") gives ['a', '', 'b']. ",".join(...) needs strings.
  • zip stops at the shortest input; zip(..., strict=True) raises instead. groupby only groups adjacent equal keys, so sort first.
  • Looping over a dict gives its keys in insertion order. d[k] on a defaultdict inserts k; d.get(k) doesn't. Don't add or remove keys while looping.

8 problems

Interview roadmap

esc