Shortest Distance After Road Addition Queries I - Problem

You are given an integer n and a 2D integer array queries. There are n cities numbered from 0 to n - 1.

Initially, there is a unidirectional road from city i to city i + 1 for all 0 <= i < n - 1.

queries[i] = [ui, vi] represents the addition of a new unidirectional road from city ui to city vi.

After each query, you need to find the length of the shortest path from city 0 to city n - 1.

Return an array answer where for each i in the range [0, queries.length - 1], answer[i] is the length of the shortest path from city 0 to city n - 1 after processing the first i + 1 queries.

Input & Output

Example 1 — Basic Case
$ Input: n = 5, queries = [[2,4],[0,3],[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,3]: 0→3→4 (distance 2). After [0,4]: 0→4 (distance 1).
Example 2 — Single Query
$ Input: n = 4, queries = [[0,3]]
Output: [1]
💡 Note: Initially: 0→1→2→3 (distance 3). After [0,3]: direct path 0→3 (distance 1).
Example 3 — No Improvement
$ Input: n = 4, queries = [[1,3],[2,0]]
Output: [2,2]
💡 Note: Initially: 0→1→2→3 (distance 3). After [1,3]: 0→1→3 (distance 2). After [2,0]: still shortest is 0→1→3 (distance 2).

Constraints

  • 3 ≤ n ≤ 500
  • 1 ≤ queries.length ≤ 500
  • queries[i].length == 2
  • 0 ≤ ui < vi < n
  • 1 < vi - ui

Visualization

Tap to expand
Shortest Distance After Road Addition QueriesInitial Graph (n=5):01234Distance 0→4: 4 stepsAfter Query [2,4]:01234New shortcut!Distance 0→4: 3 steps (0→1→2→4)After Query [0,4]:Distance 0→4: 1 step (0→4 direct)Output: [3, 2, 1]
Understanding the Visualization
1
Initial State
Cities connected sequentially: 0→1→2→3→4
2
Add Roads
New roads create shortcuts between cities
3
Find Shortest
BFS finds shortest path after each addition
Key Takeaway
🎯 Key Insight: Each new road can potentially create a shorter path, so we need to recalculate the shortest distance using BFS after each addition
Asked in
Google 15 Meta 12 Amazon 10 Microsoft 8
12.5K Views
Medium Frequency
~25 min Avg. Time
287 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