Topological Sort

Order the nodes of a directed acyclic graph with Kahn's algorithm or DFS, and use it for scheduling and dependency problems.

Intermediate · about 5 hours · difficulty 3/5

Learn first: Graph Representation, BFS and DFS

Topological sort lists the nodes of a DAG so that every edge goes from earlier to later. Any problem about prerequisites, build orders or dependencies is probably this.

Two algorithms

  • Kahn's algorithm (BFS): compute in-degrees, push all zero in-degree nodes, pop and decrement neighbours. If you process fewer than n nodes, there is a cycle.
  • DFS-based: push a node onto a stack after visiting all its descendants; reverse the finishing order.

Key patterns

  • Cycle detection in a directed graph (Course Schedule).
  • Producing an order (Course Schedule II).
  • Alien Dictionary: build edges from the first differing character of adjacent words.
  • Longest path in a DAG via DP over the topological order.
  • Find Eventual Safe States: reverse the graph and run Kahn's.
  • Parallel scheduling: minimum semesters = number of BFS levels (Parallel Courses).

Pitfalls

  • In Alien Dictionary, missing the invalid case where a longer word appears before its own prefix.
  • Using undirected cycle detection logic on a directed graph.

You are ready to move on when you can implement Kahn's algorithm from memory and use it to detect a cycle.

Key concepts

  • DAGs and in-degree
  • Kahn's algorithm
  • DFS finishing order
  • Cycle detection in directed graphs
  • Alien Dictionary
  • DP on a DAG

Mini project

Solve these 8 in 7 days, log time and pattern: Course Schedule, Course Schedule II, Find Eventual Safe States, Alien Dictionary, Parallel Courses, Minimum Height Trees, Longest Increasing Path in a Matrix, Course Schedule (CSES).

Check yourself

How does Kahn's algorithm tell you that the graph has a cycle?

Free resources