Topological Sort (DFS) Problem

Topological Sort (DFS) Problem — ExecCode Medium DSA Practice

Solve the Topological Sort (DFS) 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 a directed acyclic graph with n nodes labeled 0..n-1 and a list of directed edges, return one valid topological ordering using DFS: push each node onto a stack when its DFS finishes, then reverse the stack.

Examples

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

Constraints

1 ≤ n ≤ 10^5 0 ≤ edges.length ≤ min(n(n-1), 210^5) edges[i] = [u, v] means directed edge u → v Graph is a DAG (no cycles)

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