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

Graphs

BFS / multi-source BFS

Level-by-level search; seed the queue with every source.

Notes

Recognise it when: shortest path in steps on an unweighted graph or grid, "minimum minutes/moves", spreading, level-by-level processing.

q = deque(sources)            # multi-source: seed ALL starts
seen = set(sources)
steps = 0
while q:
    for _ in range(len(q)):   # one level
        node = q.popleft()
        for nxt in neighbours(node):
            if nxt not in seen:
                seen.add(nxt)
                q.append(nxt)
    steps += 1

Gotchas

  • Mark nodes seen when you enqueue them, not when you dequeue them, or you get duplicates.
  • For simultaneous updates (cellular automata), BFS levels give you that for free. Never re-scan the whole grid each step.

14 problems

Interview roadmap

Graphs Grids and networks: BFS, DFS, cycles, ordering.

BFS / multi-source BFS guide

esc