Back to Practice
#0254

Network Delay Time

MediumDSA28 min20 XP

Problem

Given directed edges [u, v, w], n nodes labeled 1 to n, and source k, return the time for all nodes to receive the signal, or -1 if some node is unreachable.

Why This Matters

Dijkstra is the default shortest-path tool when edges have non-negative weights.

Function Signature

def network_delay_time(times, n, k):

Examples

Example 1
Inputtimes = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
Output2

Node 4 receives the signal after 2 total time through 2 -> 3 -> 4.

Constraints

  • Return the exact requested value.
  • Handle empty or small inputs when the prompt allows them.
  • Prefer the target DSA pattern over brute force when the input can grow.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 3 hidden categories
Reachable graph
Inputsource 2
Expected2

The farthest shortest distance is 2.

Unreachable node
Inputn = 2, edge 1 -> 2, source 2
Expected-1

Node 1 cannot be reached from node 2.

Hidden Test Categories
multiple edges from same nodesingle node graphlonger indirect path beats direct path