Both problems were essentially the same pattern so once I got the first one down the second was just a variation.
Model the courses and prerequisites as a directed graph where an edge from prerequisite to course indicates dependency. Then detect if the graph contains a cycle using either Kahn's algorithm (BFS topological sort) or DFS with recursion stack. If a cycle exists, it's impossible to finish all courses; otherwise, it's possible.
Pro tip: Discuss both BFS and DFS approaches, mentioning their time and space complexities, and explain why cycle detection is equivalent to checking if a topological ordering exists. Also, clarify edge cases like duplicate prerequisites or disconnected graphs.
Restate the problem: given numCourses and a list of prerequisite pairs, determine if all courses can be finished. Clarify that a cycle in the prerequisite graph makes it impossible.
Represent courses as nodes and prerequisites as directed edges. For each pair [a, b] meaning b is prerequisite for a, add edge b -> a. Build an adjacency list and optionally an in-degree array.
Select either Kahn's algorithm (BFS topological sort) or DFS with recursion stack. Explain the chosen method's steps and why it detects cycles.
Write code for the chosen algorithm, ensuring to handle disconnected components. Analyze time complexity O(V+E) and space complexity O(V+E).
Test with cases: no prerequisites, simple cycle, complex graph. Conclude that if no cycle is found, all courses can be finished.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.