A network has n nodes, numbered 1 to n. Each entry of times is [u, v, w]: a one-way link that carries a signal from node u to node v in w time units.
A signal leaves node k at time 0 and spreads along every link. Return how long it takes until every node has received it. If some node can never receive it, return −1.
Example 1
Input: times = [[1,2,4],[1,3,1],[3,2,2],[2,4,1],[3,4,6]], n = 4, k = 1 Output: 4 Why: node 4 is last, at 1 + 2 + 1 via nodes 3 and 2
2 more examples and the constraints
Example 2
Input: times = [[2,1,5],[2,3,3]], n = 3, k = 2 Output: 5 Why: node 1 hears it at 5, node 3 at 3
Example 3
Input: times = [[1,2,2],[3,1,1]], n = 3, k = 1 Output: -1 Why: no link leads into node 3
Constraints
- 1 ≤ k ≤ n ≤ 100
- 1 ≤ length of times ≤ 6,000, and no link repeats
- 1 ≤ u, v ≤ n, u ≠ v, and 0 ≤ w ≤ 100
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Bellman-FordO(n · E)
- Dijkstra with a min-heapO(E log E)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100 nodes and 6,000 links | Verdict |
|---|---|---|---|
| Bellman-Ford | O(n · E) | Correct; reads every link n − 1 times | |
| Dijkstra with a min-heap | O(E log E) | Best; each link used once |
n = nodes, E = links in times.
Edge cases to test
- Unreachable node. A node with no way in from k means the answer is −1.
- Links are one-way. [[2, 1, 7]] with k = 1 never reaches node 2.
- Zero-time links. w = 0 is allowed; the answer can be 0.
- More hops, less time. Three links of 5 beat one link of 50; the first route found is not always the best.
- Cycles. A link back to a settled node must be skipped, or the search never ends.
Common mistakes
- Returning the sum of all arrival times instead of the largest one.
- Settling a node when it is pushed rather than when it is popped, which locks in a slower route.
- Forgetting to check that every node was reached before returning the maximum.
How to talk through it
- 1Clarify. Are links one-way? Can a time be 0? What if a node can never be reached?
- 2Reframe it. Each node hears the signal at its shortest-path time from k; the answer is the largest of those.
- 3Give Bellman-Ford. Relax every link n − 1 times; correct, but O(n · E).
- 4Code Dijkstra. Min-heap of (time, node); the first pop of a node is final because no weight is negative.
- 5Test out loud. Run the unreachable node and the case where more hops win before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?