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 Queries INPUT Initial Graph (n=5 cities) 0 1 2 3 4 0 --> 1 --> 2 --> 3 --> 4 Initial distance: 4 Parameters: n = 5 Queries: Query 1: [2, 4] Query 2: [0, 3] Query 3: [0, 4] Add road from u to v Find shortest path 0 to n-1 ALGORITHM STEPS 1 Build Adjacency List Init graph: i --> i+1 edges 2 Process Each Query Add edge u --> v to graph 3 Run BFS from 0 Find shortest path to n-1 4 Store Result Append distance to answer BFS After Each Query: Q1: Add 2-->4 Path: 0-->1-->2-->4 = 3 Q2: Add 0-->3 Path: 0-->3-->4 = 2 Q3: Add 0-->4 Path: 0-->4 = 1 BFS finds optimal path each time FINAL RESULT Final Graph State: 0 1 2 3 4 Best path: 0 --> 4 (length 1) Output Array: 3 2 1 Q1 Q2 Q3 answer = [3, 2, 1] OK - All queries processed Time: O(Q * (V + E)) Space: O(V + E) Key Insight: BFS is optimal for unweighted graphs because it explores nodes level by level, guaranteeing the shortest path is found first. Each query adds an edge that can only decrease (or maintain) the shortest distance. The graph is incrementally updated, so we recompute BFS after each addition. Constraint: New roads go forward (u < v), so no cycles that could trap BFS. TutorialsPoint - Shortest Distance After Road Addition Queries I | Efficient BFS with Graph Updates
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