DSA interview question
A student must take numCourses courses. Each prerequisite pair [a, b] means course b must be taken before course a. Can the student finish every course? That's possible exactly when the prerequisite graph (edges b → a) has no directed cycle. Kahn's algorithm answers it directly. Keep taking a course with no unmet prerequisites (in-degree 0), unlock the courses that depend on it, and check whether all courses end up taken.
Example: numCourses = 2, [[1, 0]] → true; [[1, 0], [0, 1]] → false.
bool canFinish(int numCourses, const vector<vector<int>>& prerequisites); // [a, b]: b before a
Input (numCourses, prerequisites) | Output | Explanation |
|---|---|---|
(2, [[1,0]]) | true | Take 0, then 1 |
(2, [[1,0],[0,1]]) | false | Each requires the other |
(3, [[1,0],[2,1]]) | true | 0 → 1 → 2 |
(4, [[1,0],[2,1],[3,2],[1,3]]) | false | 1 → 2 → 3 → 1 |
(1, []) | true |
(Confirm: [a, b] means b must come before a; there are no duplicate pairs.)
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