ExamAdda Logo

Network Delay Time

Easy

You are given n nodes numbered from 1 to n.

You are also given a list of directed edges:

times[i] = [u, v, w]

 

which means a signal takes w units of time to travel from node u to node v.

A signal is sent from node k.

Return the minimum time required for all nodes to receive the signal.

If it is impossible for every node to receive the signal, return:

-1

 

Example

n = 4

k = 2

times =

[2,1,1]

[2,3,1]

[3,4,1]

 

The signal travels:

2 → 1 = 1

2 → 3 = 1

3 → 4 = 1

 

So the farthest node receives the signal after:

1 + 1 = 2

 

Therefore:

2

 

Main Idea

This is a Shortest Path problem with weighted edges.

Since all edge weights are positive, we can use Dijkstra's Algorithm.

Steps

  1. Build an adjacency list.
  2. Set the distance of the starting node k to 0.
  3. Put (0, k) into a min-priority queue.
  4. Take the node with the smallest known distance.
  5. Relax all its outgoing edges.
  6. Continue until the queue is empty.
  7. Find the maximum shortest distance among all nodes.
  8. If any node is unreachable, return -1.

The answer is:

maximum shortest distance

Example 1

Input

4 3 2
2 1 1
2 3 1
3 4 1

Output

2

Explanation

Starting from node 2:

2 → 1 = 1

2 → 3 = 1

3 → 4 = 1

 

Shortest distances are:

1 → 1

2 → 0

3 → 1

4 → 2

 

The maximum distance is 2.

Therefore, all nodes receive the signal in:

2

Example 2

Input

2 1 1
2 1 1

Output

-1

Explanation

The signal starts from node 1.

The only edge is:

2 → 1

 

There is no path from node 1 to node 2.

Therefore, node 2 never receives the signal.

Answer:

-1

Constraints

1 <= n <= 100
1 <= times.length <= 6000
times[i].length == 3
1 <= ui
vi <= n
ui != vi
0 <= wi <= 100
All pairs (ui
vi) are unique.

Hints:

Hint 1

The signal can travel through multiple intermediate nodes.

So you need the shortest path from k to every other node.

Hint 2

Use Dijkstra's Algorithm because all edge weights are non-negative.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 16, 2026

Last updated

Aug 17, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output