PPractick

DSA interview question

Course Schedule I

Hard · Data structures · Topics: graph, dfs, topological sort

The problem

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.

Function signature

bool canFinish(int numCourses, const vector<vector<int>>& prerequisites);  // [a, b]: b before a

Test cases

Input (numCourses, prerequisites)OutputExplanation
(2, [[1,0]])trueTake 0, then 1
(2, [[1,0],[0,1]])falseEach requires the other
(3, [[1,0],[2,1]])true0 → 1 → 2
(4, [[1,0],[2,1],[3,2],[1,3]])false1 → 2 → 3 → 1
(1, [])true

(Confirm: [a, b] means b must come before a; there are no duplicate pairs.)

How interviewers phrase it

Clarifying questions to ask

  1. Which direction is [a, b]? (b before a, so the edge is b → a.)
  2. Can there be self-prerequisites like [x, x]? (That's a cycle, so false.)
  3. Do I need the order too? (No: that's Course Schedule II.)

Follow-ups to expect

  1. "What is this really?"
  2. **"Why does the edge go b
  3. "DFS alternative?"
  4. "Returning an order?"
  5. "Complexity?"

Practise questions like this with a real engineer

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 interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in