#3244
Shortest Distance After Road Addition Queries II
HardArrayGreedyGraph TheoryOrdered SetDynamic ProgrammingGraph Theory
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses a dynamic programming technique to maintain the shortest distances from city 0 to all other cities. By updating only the necessary distances after each query, we achieve a more efficient solution.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an array to store the shortest distances from city 0 to all cities, starting with distances to direct neighbors.
- 2Step 2: For each query, update the distance for the destination city if the new road provides a shorter path.
- 3Step 3: After processing each query, store the distance to city n-1 in the results.
solution.py9 lines
1def shortest_distance_optimal(n, queries):
2 dist = [float('inf')] * n
3 dist[0] = 0
4 results = []
5 for u, v in queries:
6 if dist[u] + 1 < dist[v]:
7 dist[v] = dist[u] + 1
8 results.append(dist[n - 1])
9 return resultsℹ
Complexity note: The time complexity is linear because we only process each query once and update the distances in constant time. The space complexity is linear due to the distance array.
- 1Understanding how to efficiently update paths in a graph is crucial for optimizing solutions.
- 2Dynamic programming can significantly reduce the time complexity when dealing with cumulative updates.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.