Topological Sort (Kahn) Problem

Topological Sort (Kahn) Problem — ExecCode Medium DSA Practice

Solve the Topological Sort (Kahn) problem on ExecCode. Free online medium DSA practice in Arrays - Basics. Write and run code in Java, C++, Python — no signup required to run.

Problem description

Given the same DAG as DFS topo (n nodes, directed edges), return one valid topological ordering using Kahn’s algorithm: repeatedly remove indegree-0 nodes via BFS.

Examples

Input n = 7, edges = [[5, 2], [5, 0], [4, 0], [4, 1], [2, 3], [3, 1], [4, 6], [5, 6]]; Output [4, 5, 2, 0, 6, 3, 1]. Input n = 2, edges = [[0, 1], [1, 0]]; Output []

Constraints

1 ≤ n ≤ 10^5 0 ≤ edges.length ≤ min(n(n-1), 210^5) edges[i] = [u, v] means directed edge u → v If a cycle exists, return []

Practice Topological Sort (Kahn) free on ExecCode. Browse DSA problems, topic map, and placement guides.