Shortest path · Medium
A routing service models one-way delivery links between hubs. Every link has a non-negative integer cost. For a selected source hub, the planner needs the cheapest cost to every hub, including those that cannot be reached.
Return minimum directed path costs from source in hub-ID order. Do not return paths or confuse a direct link with the cheapest multi-link route.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
A JSON object { "n": number, "edges": [number,number,number][], "source": number }.
Fields
- n is the number of hubs, numbered 0 through n - 1.
- Each edge is [from,to,cost] and can be used only in that direction.
- source is a valid hub ID when n > 0. The empty graph uses source = 0 and edges = [].
Output
Return value
- Return an array of length n: result[i] is the minimum sum of costs to hub i.
- The source costs 0. A reachable zero-cost path returns 0 rather than null.
- An unreachable hub returns null, not Infinity or -1.
- Parallel links and self-links are allowed. For n = 0 return [].
Constraints
- 0 <= n <= 100000 and 0 <= edges.length <= 200000.
- 0 <= cost <= 1000000000 and all endpoints are valid.
- Shortest finite costs fit in a JavaScript safe integer: a simple path costs at most 99999000000000.
- Negative links and negative cycles are outside the contract.
Examples
Example 1
{
"edges": [
[
0,
1,
9
],
[
0,
2,
2
],
[
2,
1,
3
]
],
"n": 4,
"source": 0
}Returns
[
0,
5,
2,
null
]The route 0 → 2 → 1 costs 5; hub 3 is unreachable.
Example 2
{
"edges": [
[
0,
1,
0
]
],
"n": 2,
"source": 0
}Returns
[
0,
0
]Zero cost is different from unreachable.
Required complexity
O((n + m) log(n + m + 1)) time and O(n + m) extra space or better