Find a valid dependency order
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Take-home Project
Quick Answer: This question evaluates understanding of directed graphs, dependency resolution and cycle detection, and the ability to reason about valid ordering constraints within a graph representation.
Constraints
- 0 <= n <= 10^5
- 0 <= len(dependencies) <= 2 * 10^5
- Each dependency is a pair [a, b] such that 0 <= a, b < n
Examples
Input: (4, [[1,0],[2,0],[3,1],[3,2]])
Expected Output: [0, 1, 2, 3]
Explanation: Task 0 must come before 1 and 2, and both 1 and 2 must come before 3. The reference solution processes available tasks in queue order and returns [0, 1, 2, 3].
Input: (5, [[1,0],[2,0],[4,3]])
Expected Output: [0, 3, 1, 2, 4]
Explanation: Tasks 0 and 3 have no prerequisites initially. Processing them in order yields [0, 3, 1, 2, 4], which satisfies all dependencies.
Input: (2, [[0,1],[1,0]])
Expected Output: []
Explanation: Task 0 depends on 1 and task 1 depends on 0, forming a cycle. No valid ordering exists.
Input: (3, [])
Expected Output: [0, 1, 2]
Explanation: There are no dependencies, so any ordering is valid. The reference solution returns tasks in increasing order.
Input: (0, [])
Expected Output: []
Explanation: With no tasks, the valid ordering is the empty list.