progress

~/problems / Graphs / Topological sort (Kahn's)

Check a topological order

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

Before writing Kahn's algorithm, be crisp about what a topological order is. There are tasks 0 .. n-1, and each pair (u, v) in edges means u must come before v.

Implement is_topological_order(n, edges, order) -> bool: True exactly when

  • order contains every task 0 .. n-1 exactly once, and
  • for every edge (u, v), u appears earlier in order than v.
edges = [(0, 2), (1, 2), (2, 3)]
is_topological_order(4, edges, [1, 0, 2, 3])   # True  (0 and 1 can go in either order)
is_topological_order(4, edges, [0, 2, 1, 3])   # False (2 comes before its prerequisite 1)
is_topological_order(4, edges, [0, 1, 2])      # False (task 3 is missing)

Up to 10^5 tasks and 2 * 10^5 edges; edges may repeat, and a self-loop (v, v) can never be satisfied.

⭐ Bonus: a speed test with 100,000 tasks earns a star in O(n + E): don't call order.index(...) for every edge.

Show hint

record pos[task] = index once; then each edge just needs pos[u] < pos[v].

Topic: Topological sort (Kahn's). BFS over in-degree-0 nodes; leftover nodes mean a cycle.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc