DSA interview question
The course planner now has to print an actual order in which to take all numCourses courses, given prerequisite pairs [a, b] (b before a), or return an empty list if it's impossible. That's a topological sort of the graph with edges b → a. Kahn's algorithm builds the order directly: repeatedly take a course whose prerequisites are all done, and if some courses are never freed, a cycle makes the schedule impossible.
Example: 4, [[1,0],[2,0],[3,1],[3,2]] → [0, 1, 2, 3].
vector<int> findOrder(int numCourses, const vector<vector<int>>& prerequisites); // empty if impossible
Input (numCourses, prerequisites) | Output (queue seeded in index order) | Explanation |
|---|---|---|
(2, [[1,0]]) | [0, 1] | |
(4, [[1,0],[2,0],[3,1],[3,2]]) | [0, 1, 2, 3] | [0, 2, 1, 3] is also valid |
(3, [[0,1],[0,2]]) | [1, 2, 0] | 0 needs both 1 and 2 |
(2, [[0,1],[1,0]]) | [] | A cycle |
(1, []) | [0] |
(Confirm: [a, b] means b before a; any valid order is accepted, and the one shown uses a FIFO queue seeded in index order.)
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