You are given n services labeled from 0 to n - 1, a list of directed dependency edges where edges[i] = [u, v] means service u must complete before service v can start, and an array times where times[i] is the execution time of service i.
The services form a directed acyclic graph (DAG). The critical path is the longest path (by total execution time) from any source service (a service with no dependencies) to any sink service (a service with no dependents). This path determines the minimum total time to complete all services when independent services can run at the same time.
Return an array where the first element is the total latency of the critical path, followed by the ordered list of service indices along that path.
Function Signature
def critical_path(n: int, edges: list[list[int]], times: list[int]) -> list[int]:
Rules
-
An edge
[u, v]
points from
u
to
v
, and
u
runs first.
-
The total time of a path is the sum of
times[i]
over every service on it, including the first and the last. Edges add no time of their own.
-
A service with no edges at all is both a source and a sink, so on its own it forms a path of one service.
-
When several critical paths have the same total time, return the one whose index sequence is lexicographically smallest: compare the sequences element by element, and the first position where they differ decides in favor of the smaller index.
Constraints
-
1 <= n <= 10^4
-
0 <= len(edges) <= 5 * 10^4
-
0 <= edges[i][0], edges[i][1] < n
-
1 <= times[i] <= 10^4
-
The graph is a valid DAG (no cycles).
Examples
Input: n = 6, edges = [[0, 2], [1, 2], [2, 3], [2, 4], [3, 5], [4, 5]], times = [3, 2, 5, 4, 6, 2]
Output: [16, 0, 2, 4, 5]
The critical path is 0 -> 2 -> 4 -> 5 with total latency 3 + 5 + 6 + 2 = 16. The other paths are shorter: 1 -> 2 -> 4 -> 5 totals 15 and 0 -> 2 -> 3 -> 5 totals 14.
Input: n = 4, edges = [[0, 1], [0, 2], [1, 3], [2, 3]], times = [1, 10, 2, 3]
Output: [14, 0, 1, 3]
The critical path is 0 -> 1 -> 3 with total latency 1 + 10 + 3 = 14. The branch through service 2 totals only 1 + 2 + 3 = 6.
Input: n = 5, edges = [[0, 1], [0, 2], [1, 3], [2, 3], [4, 3]], times = [1, 3, 3, 2, 4]
Output: [6, 0, 1, 3]
All three source-to-sink paths, 0 -> 1 -> 3, 0 -> 2 -> 3 and 4 -> 3, total 6. The tie rule picks [0, 1, 3]: it starts with the smallest index, and at the second position 1 is smaller than 2.