← Amazon Interview Insights

Amazon·Software Engineer·Onsite - Coding / Algorithms·Intermediate

Intermediate
Jun 2026

Summary

Amazon coding round, one question, classic graph problem. Nothing too wild but topological sort is one of those things you either remember cold or you don't.

Questions Asked (1)

Q1

Given a list of courses with prerequisites, determine if a valid course ordering exists and return the order if so.

Algorithms & Data Structures
Author's notes

BFS topological sort.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Model the courses and prerequisites as a directed graph and use topological sorting to detect cycles and produce a valid order. Explain that if a cycle exists, no valid ordering is possible; otherwise, return the topological order. Discuss both Kahn's algorithm (BFS) and DFS-based approaches, and analyze time and space complexity.

Pro tip: Clarify edge direction upfront: an edge from prerequisite to course ensures correct ordering. Mention that Kahn's algorithm naturally detects cycles when the processed count is less than the total courses.

1. Model as a Graph

Represent each course as a node and each prerequisite as a directed edge from the prerequisite to the course. Build an adjacency list and compute in-degrees for all nodes.

2. Choose Topological Sort Algorithm

Select either Kahn's algorithm (BFS with a queue) or DFS with cycle detection. Explain the trade-offs: Kahn's is iterative and easy to detect cycles; DFS uses recursion and can be simpler to code.

3. Execute Algorithm and Detect Cycles

For Kahn's: repeatedly remove nodes with in-degree 0, add to order, and decrement in-degrees of neighbors. If the final order size is less than the number of courses, a cycle exists. For DFS: track visited and recursion stack to detect back edges.

4. Return Result

If no cycle, return the topological order as the valid course sequence. If a cycle exists, return an empty list or indicate impossibility.

5. Analyze Complexity

State that both approaches run in O(V + E) time and O(V + E) space, where V is the number of courses and E is the number of prerequisites.

Key Points to Mention

  • Directed graph representation with adjacency list and in-degree array
  • Topological sorting using Kahn's algorithm (BFS) or DFS
  • Cycle detection: if processed nodes < total nodes, a cycle exists
  • Time and space complexity: O(V + E)
  • Handling edge cases: empty input, no prerequisites, multiple valid orders
  • Clarify edge direction: prerequisite -> course

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.