Network Delay Time
Given n nodes (1 to n), times array [u, v, w] (edge from u to v with weight w) and starting node k, find minimum time for all nodes to receive signal Return -1 if impossible Example: n = 4, times = [[2,1,1],[2,3,1],[3,4,1]], k = 2 => 2
A network has n nodes labeled 1 to n and a list of directed edges times, where [u, v, w] means a signal sent from node u reaches node v after w time units. A signal starts at node k, with 1 <= k <= n, and every w is non-negative. Return the earliest time by which every node has received the signal, or -1 if some node can never receive it.
Examples
You write
network_delay_time(times: List[List[int]], n: int, k: int)
Example 1
- Input
- times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
- returns
- 2
Example 2
- Input
- times = [[1,2,1]], n = 2, k = 1
- returns
- 1
The pattern behind it
BFS & DFS
I reach for it when
- You walk a grid, a graph or a tree and visit each cell once.
- The word shortest appears and every step costs the same.
Say this before you type. Say why breadth or depth fits, and exactly when a cell counts as visited.
All 52 BFS & DFS problemsGraphs
I reach for it when
- The input is edges, prerequisites or connections.
- You need cycles, an ordering or connected groups.
Say this before you type. Say whether the edges are directed, and which of the three jobs you are doing.
All 32 Graphs problems
Meet Coco
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.