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) == numCoursesas 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.dequefor 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.