Order Tasks with Dependencies Using a Deterministic Topological Sort
Company: OpenAI
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: Return the lexicographically smallest valid task order from a directed acyclic dependency graph, including disconnected and prerequisite-free tasks.
Constraints
- 0 <= n <= 100000.
- 0 <= len(dependencies) <= 200000.
- Every referenced task ID is in [0, n).
- There are no repeated dependency pairs or self-dependencies.
- The graph is guaranteed to be acyclic.
- Each dependency is a pair [task, prerequisite] meaning prerequisite must occur before task.
- All values fit in a 32-bit signed integer; no value exceeds 2^31 - 1.
Examples
Input: (0, [])
Expected Output: []
Explanation: Minimum valid input: zero tasks produce an empty order.
Input: (1, [])
Expected Output: [0]
Explanation: Singleton: the only task has no prerequisites.
Hints
- A task may be placed only once every one of its prerequisites has been placed. How many unplaced prerequisites does each task have at the start, and how does that count change as you place tasks?
- At many steps more than one task is legal. The lexicographic rule compares orders at the first position where they differ, which pins down exactly which of the legal tasks you must place next.
- Tasks that no pair mentions still belong in the output, and n can be zero.