Skip to the solution
MediumDSA12 min read

How do you solve the course schedule (prerequisites) problem?

1.1k views

The problem

Question presented to candidate: "There are numCourses courses labelled 0 to numCourses - 1, and a list of pairs [a, b] meaning you must take course b before course a. Can you finish all the courses? If so, give me one valid order. Please code it in Python."

What a strong answer should cover:

  • Model it as a directed graph with an edge b -> a for each pair, and recognise that "can finish" means "the graph has no cycle".
  • Kahn's algorithm: in-degree counts, a queue of courses with no remaining prerequisites, and len(order) == numCourses as the cycle test; the same function answers both Course Schedule I and II.
  • O(V + E) time and space, compared with the O(V * (V + E)) rescan brute force.
  • The DFS three-colour alternative, and the follow-up of minimum semesters via level-by-level Kahn.
  • Python specifics: collections.deque for the queue, [[] for _ in range(n)] (not [[]] * n) for adjacency, all(...) in the brute force, and the 1000-frame default recursion limit if you choose DFS.

Clarifying questions expected:

  • "Does [a, b] mean b comes before a?"
  • "Do you want just true/false, or an order โ€” and is any valid order acceptable?"
  • "Can pairs repeat, or can a course list itself?"

Code / implementation expected: Yes โ€” findOrder (and canFinish on top of it) in Python, using Kahn's algorithm.

  • graphs
  • topological-sort

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read ยท 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythoncanFinish and findOrder on normal, cyclic and tricky inputs
PythonBrute-force rescan vs Kahn step counts, plus minimum semesters

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 45 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you add two numbers stored as linked lists?

Continue