MediumDepth-First SearchBreadth-First SearchGraphHeap (Priority Queue)Shortest Path

Network Delay Time

LeetCode
1 approach, code in all languages

You are given a network of `n` nodes labeled from `1` to `n`. Travel times are described by a list `times`, where each entry `times[i] = [u, v, w]` means a signal takes `w` units of time to travel along a directed edge from node `u` to node `v`.

A signal is emitted from a single source node `k`. Return the amount of time it takes for the signal to reach every node in the network. If it is impossible for at least one node to receive the signal, return `-1`.

Because a node lights up as soon as the signal first arrives, the time for the whole network to be covered is the latest of all the individual arrival times.

Example 1

Input: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2

Output: 2

From node 2 the signal reaches node 1 at time 1 and node 3 at time 1, then continues from 3 to node 4 at time 2. The slowest arrival is 2.

Example 2

Input: times = [[1,2,1]], n = 2, k = 2

Output: -1

The only edge points from 1 to 2, so starting at node 2 there is no way to reach node 1. One node stays unreachable, so the answer is -1.

Constraints

  • 1 <= k <= n <= 100
  • 1 <= times.length <= 6000
  • times[i].length == 3
  • 1 <= u_i, v_i <= n
  • u_i != v_i
  • 0 <= w_i <= 100
  • All pairs (u_i, v_i) are unique (no multiple edges).
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now