Loading...
Loading...
1 <= n <= 2000 0 <= prerequisites.length <= 5000 prerequisites[i].length == 2 0 <= prerequisites[i][0], prerequisites[i][1] < n All pairs in prerequisites are unique prerequisites[i][0] != prerequisites[i][1]
A tech company is helping its staff software engineers apply for work visas. Each engineer has a list of prerequisite visa documents that must be approved before their application can proceed. Your task is to determine the order in which visa applications should be processed, or report if it's impossible due to circular dependencies.
This is essentially a topological sort problem where engineers are nodes and document dependencies form directed edges.
You are given n engineers numbered from 0 to n-1. You are also given a list of prerequisites where prerequisites[i] = [a, b] means engineer a's visa application depends on engineer b's application being approved first.
Return a valid processing order of all n engineers. If no valid order exists (i.e., there is a circular dependency), return an empty array [].
n (integer): the number of engineersprerequisites (list of pairs): each pair [a, b] means engineer b must be processed before engineer aReturn a list of integers representing a valid topological ordering of engineers 0 to n-1. If multiple valid orderings exist, return any one of them. If no valid ordering exists, return [].
Input: n = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
Output: [0, 1, 2, 3] or [0, 2, 1, 3]
Explanation: Engineer 0 has no dependencies, so they go first. Engineers 1 and 2 both depend on 0, so they come next (in any order). Engineer 3 depends on both 1 and 2, so they go last.
Input: n = 2, prerequisites = [[1,0]]
Output: [0, 1]
Explanation: Engineer 0 must be processed before engineer 1.
Input: n = 2, prerequisites = [[0,1],[1,0]]
Output: []
Explanation: Engineer 0 depends on 1 and engineer 1 depends on 0. This circular dependency makes it impossible to determine a valid processing order.
n nodes, a cycle exists — return [].Time Complexity: O(V + E) where V = engineers, E = prerequisites.