#743
Network Delay Time
MediumDepth-First SearchBreadth-First SearchGraph TheoryHeap (Priority Queue)Shortest PathDijkstra's AlgorithmGraph Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O((E + V) log V) |
| Space | O(1) | O(V) |
💡
Intuition
Time O((E + V) log V)Space O(V)
The optimal solution uses Dijkstra's algorithm, which efficiently finds the shortest paths from the starting node to all other nodes in a graph with non-negative weights. This approach is faster than brute force because it prioritizes exploring the shortest paths first.
⚙️
Algorithm
5 steps- 1Step 1: Create a priority queue to store nodes along with their current travel time.
- 2Step 2: Initialize the queue with the starting node and its time (0).
- 3Step 3: While the queue is not empty, extract the node with the smallest time, mark it as visited, and update the times for its neighbors.
- 4Step 4: If a neighbor can be reached in a shorter time, update its time and add it to the queue.
- 5Step 5: After processing all nodes, return the maximum time from the starting node to all other nodes, or -1 if any node is unreachable.
solution.py22 lines
1# Full working Python code
2import heapq
3from collections import defaultdict
4
5def networkDelayTime(times, n, k):
6 graph = defaultdict(list)
7 for u, v, w in times:
8 graph[u].append((v, w))
9 min_time = [float('inf')] * (n + 1)
10 min_time[k] = 0
11 pq = [(0, k)] # (time, node)
12 while pq:
13 curr_time, curr_node = heapq.heappop(pq)
14 if curr_time > min_time[curr_node]:
15 continue
16 for neighbor, weight in graph[curr_node]:
17 time = curr_time + weight
18 if time < min_time[neighbor]:
19 min_time[neighbor] = time
20 heapq.heappush(pq, (time, neighbor))
21 result = max(min_time[1:])
22 return result if result < float('inf') else -1ℹ
Complexity note: This complexity arises because we process each edge and node, and the priority queue operations take logarithmic time relative to the number of nodes.
- 1Understanding graph traversal is crucial for solving shortest path problems.
- 2Using a priority queue helps efficiently manage the exploration of nodes based on the shortest known distance.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.