← Amazon Interview Insights

Amazon·Software Engineer·Online Assessment (OA)·Intermediate

Intermediate
Jul 2026

Summary

Amazon SWE online assessment, one coding problem centered on topological sort. Pretty standard graph question but the output format tripped me up a bit.

Questions Asked (1)

Q1

Given n courses and m prerequisite pairs, determine if all courses can be completed. If yes, output a valid ordering; if not, output IMPOSSIBLE.

Algorithms & Data Structures
Author's notes

Basically Kahn's algorithm with a small twist: you also need to reconstruct the order, not just detect cycles.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Model the courses and prerequisites as a directed graph, then perform a topological sort using Kahn's algorithm (BFS) or DFS. If the topological sort includes all n courses, return the ordering; otherwise, return IMPOSSIBLE.

Pro tip: Always clarify edge cases upfront, such as duplicate prerequisite pairs, self-loops, or disconnected graphs, and mention that you'll handle them gracefully. Also, discuss the trade-offs between Kahn's algorithm and DFS-based topological sort in terms of cycle detection and implementation complexity.

1. Clarify the problem

Confirm input format, constraints (e.g., course labels 0 to n-1), and output requirements (any valid order or a specific one). Ask about edge cases like duplicate edges or cycles.

2. Build the graph

Construct an adjacency list for the directed graph and compute in-degrees for each node. Use a set or boolean matrix to handle duplicate edges if necessary.

3. Topological sort

Use Kahn's algorithm: enqueue nodes with in-degree 0, then repeatedly dequeue, add to order, and decrement in-degrees of neighbors. Alternatively, use DFS with recursion stack for cycle detection.

4. Check for cycles

After processing, if the order contains fewer than n nodes, a cycle exists, so return IMPOSSIBLE. Otherwise, return the order.

5. Analyze complexity

State that time complexity is O(n + m) and space complexity is O(n + m) for the graph and auxiliary data structures.

Key Points to Mention

  • Directed graph representation with adjacency list and in-degree array
  • Topological sorting algorithms: Kahn's (BFS) and DFS-based
  • Cycle detection: if topological order size < n, cycle exists
  • Handling duplicate edges and self-loops
  • Time and space complexity: O(n + m)
  • Edge cases: empty graph, single course, disconnected components

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