 All Problems
Topological Sort (Classic)
medium
topological sort
graph
dfs
bfs
amazon
google
microsoft
adobe

Given a Directed Acyclic Graph with V vertices (0 to V-1) and adjacency list adj, return a valid topological ordering of vertices.

In a topological ordering, for every directed edge u → v, vertex u appears before v.

Example:

Input: V=6, adj=[[2,3],[3,4],[],[4],[],[]]  (adj[i] = neighbors of i)
Output: [0,1,2,3,4,5]  (or any valid topological order)

Constraints:

  • 2 <= V <= 10^4
  • DAG guaranteed (no cycles)
Run to check your code against the sample cases, or submit to run every case