I went with the BFS in-degree approach first since it naturally handles the impossible case by just checking if you've processed all nodes.
Model the courses and prerequisites as a directed graph and perform a topological sort using Kahn's algorithm (BFS with in-degree tracking). If the topological order contains all courses, return it; otherwise, a cycle exists, so return an empty array.
Pro tip: Explicitly mention that you're using Kahn's algorithm because it naturally detects cycles (if the result size is less than the number of courses) and avoids recursion depth issues, which is important for large inputs at Amazon scale.
Confirm that prerequisites are given as pairs [a, b] meaning b before a, and that courses are labeled 0 to n-1. Build an adjacency list and an in-degree array to represent the graph.
Add all courses with in-degree 0 to a queue. These are courses with no prerequisites and can be taken first.
While the queue is not empty, dequeue a course, add it to the result, and for each neighbor, decrement its in-degree. If a neighbor's in-degree becomes 0, enqueue it.
If the result contains all courses, return it as a valid ordering. Otherwise, a cycle exists, so return an empty array.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.