Data Structures & Algorithms Advanced Graphs
💡
Exercise 119

Network Delay Time 25 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

Given a network of n nodes and weighted edges [u,v,w], find how long it takes for a signal from node k to reach all nodes. This is Dijkstra's algorithm — shortest path from a single source.

import heapq # Dijkstra: min-heap of (distance, node) # Greedily process nearest unvisited node # Update neighbors if shorter path found

Answer = max of all shortest distances. If any node unreachable, return -1.

💡 Pro tip: Understand this problem deeply — don't just memorize the code. Try explaining the approach out loud as if teaching a friend. If you can explain it simply, you truly understand it!

📋 Instructions
Find network delay time using Dijkstra's algorithm.
Use heapq with (dist, node). Pop smallest, skip if visited. Update neighbors. Answer = max of all distances.
🧪 Test Cases
Input
networkDelayTime(times, 4, 2)
Expected
2
Test case 1
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.