← TCS bank

TCS · Question 6

Topological Sort in DAG

C++code⏱ O(V+E)💾 O(V)
Service-based

Problem

Order vertices in a directed acyclic graph so that every edge u to v appears with u before v.

Approach

Kahn's BFS emits zero-indegree vertices first.

Time O(V+E)Space O(V)

How it works

  1. 1Count incoming edges per vertex.
  2. 2Emit zero-indegree vertices, freeing their neighbours.

Sample input / output

Input:
V = 6, edges = [[5,2],[5,0],[4,0],[4,1],[2,3],[3,1]]
Output:
[4, 5, 0, 2, 3, 1]

Constraints

Directed acyclic graph.

Solution — read it, then walk it

Time O(V+E)Space O(V)Loops 1Branches 1Returns 1source · C++
Scroll sideways for wide charts — the view follows the active step.
↻ repeatSTARTinclude <iostream>include <vector>include <queue>using namespace stdvector<int> topoSort(int V,const vector<vector<int>>&adj)DEFINE main()vector<vector<int>> adj ={{}, {}, {3}, {1}, {0, 1},{0, 2}}auto o = topoSort(6, adj)cout << "["for (size_t i = 0; i <o.size(); ++i)if (i) cout << ", "cout << o[i]cout << "]" << endlRETURN 0END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/15

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits