DSA interview question
A university lists courses with prerequisite edges (u → v means u must be taken before v), and the planner needs an order in which to take all courses without breaking any prerequisite: a topological order of the DAG. The DFS way: a vertex finishes only after everything reachable from it has finished. So if you push each vertex onto a stack when its DFS finishes, reversing that finish order puts every vertex before all of its descendants.
Example: 6 vertices, edges 5→2, 5→0, 4→0, 4→1, 2→3, 3→1 → [5, 4, 2, 3, 1, 0].
vector<int> topoSort(int V, const vector<vector<int>>& adj); // adj describes a DAG
Input (V, edges) | Output (DFS from 0, 1, 2, …) | Explanation |
|---|---|---|
(6, [[5,2],[5,0],[4,0],[4,1],[2,3],[3,1]]) | [5, 4, 2, 3, 1, 0] | |
(4, [[3,0],[1,0],[2,0]]) | [3, 2, 1, 0] | 0 must come last |
(5, [[0,1],[1,2],[2,3],[3,4]]) | [0, 1, 2, 3, 4] | A chain has one order |
(2, [[0,1]]) | [0, 1] | |
(3, []) | [2, 1, 0] | Any order is valid |
(Confirm: the input is a DAG; many orders are valid, and the one shown comes from starting DFS at 0, 1, 2, … in turn.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in