00:00

Problem Statement

Input/Output Examples

Visual Explanation

Choosing the smallest ready vertex with a priority queue makes Kahn's output repeatable; any choice among ready vertices would still give a valid order.

Approaches

Both approaches produce a valid order and detect cycles. Kahn's removes ready vertices; DFS uses finishing order.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. The two programs print different orders, because a graph can have many valid topological orders; each program checks its own order and prints valid=true.

Complexity Analysis

Here V is the number of vertices and E the number of edges. Both approaches process every vertex and edge once.

Interview Tips and Recommended Approach

  • Say that the answer is not unique. Test by checking edges, not by comparing with one fixed order.
  • Detect cycles by comparing the output size with the number of vertices.
  • Know the applications: build systems, course planning and spreadsheet recalculation.
  • Use a priority queue when the smallest-first (lexicographic) order is required.

Recommended Approach: Kahn's Algorithm

Why: it is iterative, detects cycles for free and makes the "ready to run" idea explicit, which matches how schedulers work.