Shortest path · Medium
A diagnostic view explains how each directed connection compares with the cheapest known costs from a selected start. Its slack is the extra cost introduced by using that edge after reaching its source optimally. Unreachable endpoints need an explicit missing value.
Return each edge’s source label and destination label with slack equal to distance[from] plus weight minus distance[to].
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ n: integer, edges: [integer, integer, integer][], source: integer }
Fields
- n is the node count and edges contains directed [from,to,weight] triples. Parallel edges are distinct input entries; self-loops are allowed.
- All weights are non-negative integers unless the task explicitly requires positive weights.
- source is the starting node. source = -1 means no starting node and yields no reachable nodes.
Output
Return value
- Return [from,to,slack] per input edge sorted by from, then to, then original weight, all ascending. Preserve parallel entries.
- Use null if either endpoint is unreachable. Zero slack means the edge is consistent with a shortest arrival; it does not prove a unique route.
Constraints
- 0 <= n <= 50000; 0 <= edges.length <= 200000; endpoints are valid node labels; 0 <= weight <= 1000000.
- source and target, when used, are either -1 or valid node labels. All distance and slack results fit a safe JSON integer.
Examples
Example 1
{
"edges": [
[
0,
2,
9
],
[
0,
1,
2
],
[
1,
2,
3
]
],
"n": 3,
"source": 0
}Returns
[
[
0,
1,
0
],
[
0,
2,
4
],
[
1,
2,
0
]
]Example 2
{
"edges": [
[
1,
2,
4
]
],
"n": 3,
"source": 0
}Returns
[
[
1,
2,
null
]
]Required complexity
O(n + m log(m + 1)) time and O(n + m) auxiliary space