CodingNodes / Advanced Graphs / Network Delay Time System design Space play · ←→ step · R restart

Problem

A network has n nodes numbered 1 to n. Each entry of times is [u, v, w]: a one-way link from node u to node v that a signal crosses in w time units.

A signal is sent from node k at time 0 and travels along every link it can. Return the time at which the last node receives it, or -1 if some node is never reached.

Constraints

  • 1 ≤ k ≤ n ≤ 100
  • 1 ≤ times.length ≤ 6000
  • times[i] = [u, v, w] with 1 ≤ u, v ≤ n and u ≠ v
  • 0 ≤ w ≤ 100, and each ordered pair (u, v) appears at most once

Examples: pick one to animate

Solutions

TimeO(E log E) SpaceO(n + E)

Time: Each link can push at most one entry, so the heap sees at most E + 1 pushes and pops, each costing about log E.

Space: The adjacency lists hold E links, and the heap holds at most E + 1 entries.

Travel times are never negative, so the first time a node is taken off a min-heap of (time, node) pairs is its final, fastest time. Pop the smallest pair; if the node is new, record it and push the pairs for its neighbours (time + w). Later duplicate pairs for the same node are stale and skipped. The last node to be settled has the largest time, which is the answer; if fewer than n nodes are settled, return −1. The code uses its own array heap (parent of index i is (i − 1) / 2), so the array and tree you see are the real thing.