~/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.
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
- Basics: check a topological order basics py · c++ · java easy
- What to rebuild, and in what order easy
- Course Schedule py · c++ · java easy
- Course Schedule II py · c++ · java easy
- Alien Dictionary py · c++ · java medium
- Spreadsheet with formula dependencies 2 levels OpenAI medium
- Inherited permissions with allow and disallow 2 levels Snowflake medium
- Best run down the mountain Airbnb medium
- Build steps that run alone DatabricksMeta py · c++ · java medium
- Minimum Height Trees py · c++ · java medium
- Course Schedule IV py · c++ · java medium