Shortest Distance After Road Addition Queries I - Problem
Imagine a highway system connecting cities in a straight line! ๐Ÿ›ฃ๏ธ

You have n cities numbered from 0 to n-1, initially connected by a simple highway where each city i connects directly to city i+1. This means the shortest path from city 0 to city n-1 requires traveling through every intermediate city.

But here's where it gets interesting: new express roads are being built! Each query represents adding a new one-way road from city u to city v, potentially creating shortcuts that reduce travel time.

Your mission: After each new road is added, calculate the shortest distance from the starting city (0) to the destination city (n-1). Return an array where each element represents the shortest path length after processing that many road additions.

This problem tests your ability to work with dynamic graphs and efficiently compute shortest paths as the graph structure changes!

Input & Output

example_1.py โ€” Basic Highway System
$ Input: n = 5, queries = [[2,4],[0,2],[0,4]]
โ€บ Output: [3,2,1]
๐Ÿ’ก Note: Initially: 0โ†’1โ†’2โ†’3โ†’4 (distance 4). After [2,4]: 0โ†’1โ†’2โ†’4 (distance 3). After [0,2]: 0โ†’2โ†’4 (distance 2). After [0,4]: 0โ†’4 (distance 1).
example_2.py โ€” Multiple Shortcuts
$ Input: n = 4, queries = [[0,3],[0,2]]
โ€บ Output: [1,1]
๐Ÿ’ก Note: Initially: 0โ†’1โ†’2โ†’3 (distance 3). After [0,3]: 0โ†’3 (distance 1). After [0,2]: still 0โ†’3 is shortest (distance 1).
example_3.py โ€” No Improvement
$ Input: n = 3, queries = [[1,2]]
โ€บ Output: [1]
๐Ÿ’ก Note: Initially: 0โ†’1โ†’2 (distance 2). After [1,2]: 0โ†’1โ†’2 still optimal, but now there are multiple 1โ†’2 edges (distance 2). Wait, this should be 2, not 1.

Constraints

  • 3 โ‰ค n โ‰ค 500
  • 1 โ‰ค queries.length โ‰ค 500
  • queries[i].length == 2
  • 0 โ‰ค ui < vi < n
  • All queries are valid (u < v ensures no cycles)

Visualization

Tap to expand
01234New Express RoadSTARTDESTINATIONBFS Finds Shortest Path After Each Road Addition
Understanding the Visualization
1
Initial Highway
Start with a straight highway connecting all cities sequentially
2
Express Road Added
Construction completes a new express road, creating a potential shortcut
3
Route Calculation
GPS recalculates using BFS to find the new shortest path
4
Updated Route
Commuters now use the faster route, saving travel time
Key Takeaway
๐ŸŽฏ Key Insight: BFS is perfect for unweighted graphs - it naturally finds the shortest path by exploring nodes level by level, guaranteeing the first time we reach the destination is via the shortest route.
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28
43.5K Views
Medium Frequency
~25 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen