Return a topological ordering of a graph
MicrosoftSoftware Engineer · Technical ScreenLast updated
This question tests the ability to implement Kahn's algorithm or a DFS-based approach to perform a topological sort while correctly handling cycle detection.
Task
Given a directed graph represented as a list of n tasks (labeled 0 to n-1) and a list of prerequisites where prerequisites[i] = [a, b] indicates that task b must be completed before task a, return a valid ordering of tasks. If no such ordering exists (i.e., there is a cycle), return an empty list.
Function Signature
def find_order(n: int, prerequisites: list[list[int]]) -> list[int]:
Constraints
1 <= n <= 20000 <= len(prerequisites) <= n * (n - 1) / 2- All prerequisite pairs are unique.
Examples
Example 1:
- Input:
n = 2,prerequisites = [[1, 0]] - Output:
[0, 1] - Explanation: Task 0 must be done before 1.
Example 2:
- Input:
n = 4,prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]] - Output:
[0, 1, 2, 3](or[0, 2, 1, 3]) - Explanation: 0 is the root, followed by 1 and 2, and finally 3.
Example 3:
- Input:
n = 2,prerequisites = [[1, 0], [0, 1]] - Output:
[] - Explanation: A cycle exists, so no valid order is possible.
Edge Cases
- Disconnected graphs (multiple components).
- Graphs with no prerequisites (any order is valid).
- Graphs containing self-loops or complex cycles.
Hints
Hint 1
Consider tracking the 'in-degree' of each node, which represents the number of incoming edges.
Hint 2
Use a queue to process all nodes that have an in-degree of zero, as these nodes have no remaining dependencies.
Hint 3
If you finish processing and the number of tasks in your result list is less than n, it implies a cycle prevented some tasks from being completed.
Follow-up questions
- How would you modify your solution to find the lexicographically smallest topological sort?
- What is the time and space complexity of your solution in terms of V (vertices) and E (edges)?
- How would the algorithm change if the input was an adjacency matrix instead of an edge list?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.