Determine feasible task ordering
Company: Adobe
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: This question evaluates knowledge of graph algorithms and dependency management, emphasizing concepts such as topological ordering and cycle detection and the ability to determine feasibility and produce a valid execution sequence.
Read the full Adobe Software Engineer interview experience this question came from
Constraints
- 1 <= n <= 10^5
- 0 <= len(dependencies) <= 10^5
- Each dependency is a pair [a, b] with 0 <= a, b < n and a != b
- There may be duplicate dependency pairs; the answer must still be a valid topological order
- Return an empty list when the tasks cannot all be completed (the dependency graph has a cycle)
Examples
Input: (2, [[1, 0]])
Expected Output: [0, 1]
Explanation: Task 1 requires task 0 first, so 0 must precede 1.
Input: (4, [[1, 0], [2, 0], [3, 1], [3, 2]])
Expected Output: [0, 1, 2, 3]
Explanation: Diamond DAG: 0 is the root, 1 and 2 depend on 0, and 3 depends on both 1 and 2. Kahn's algorithm in ascending order yields 0,1,2,3.
Hints
- Build a directed graph where the edge points from the prerequisite to the dependent: for pair (a, b), add b -> a. Then any task with in-degree 0 has no remaining prerequisites and can run now.
- Use Kahn's algorithm (BFS topological sort): start from all in-degree-0 tasks, and each time you 'complete' a task, decrement the in-degree of its dependents and enqueue any that reach 0.
- If you manage to output fewer than n tasks, some tasks are stuck in a cycle and can never be completed — return an empty list. For deterministic output, seed and process the queue in ascending index order.