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

Topological sort (Kahn's)

BFS over in-degree-0 nodes; leftover nodes mean a cycle.

Notes

Recognise it when: prerequisites, build order, task dependencies, "is there a valid order?"

indeg = [0] * n; adj = defaultdict(list)
for a, b in prereqs:        # b before a
    indeg[a] += 1; adj[b].append(a)
q = deque(i for i in range(n) if indeg[i] == 0)
order = []
while q:
    u = q.popleft(); order.append(u)
    for v in adj[u]:
        indeg[v] -= 1
        if indeg[v] == 0: q.append(v)
return order if len(order) == n else []   # leftovers = cycle

Gotchas: get the edge direction right ("[a, b] means b first"). For the lexicographically smallest order, use a heap instead of a deque.

11 problems

Interview roadmap

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

Topological sort (Kahn's) guide

esc