Shortest Distance After Road Addition Queries II - 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] = [u_i, v_i] represents the addition of a new unidirectional road from city u_i to city v_i.

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

There are no two queries such that queries[i][0] < queries[j][0] < queries[i][1] < queries[j][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 Road Addition
$ Input: n = 5, queries = [[0,3]]
Output: [2]
💡 Note: Initially: 0→1→2→3→4 (distance 4). After adding road 0→3: shortest path becomes 0→3→4 (distance 2).
Example 2 — Multiple Queries
$ Input: n = 4, queries = [[0,2],[1,3]]
Output: [2,1]
💡 Note: Initially: 0→1→2→3 (distance 3). After [0,2]: 0→2→3 (distance 2). After [1,3]: 0→2 and optimal becomes 0→2 then skip to 3 via any path giving distance 1.
Example 3 — No Improvement
$ Input: n = 3, queries = [[1,2]]
Output: [2]
💡 Note: Initially: 0→1→2 (distance 2). Adding road 1→2 doesn't create a shortcut from 0 to 2, so distance remains 2.

Constraints

  • 3 ≤ n ≤ 105
  • 1 ≤ queries.length ≤ 105
  • queries[i].length = 2
  • 0 ≤ ui < vi < n
  • There are no repeated queries

Visualization

Tap to expand
Shortest Distance After Road Addition Queries II INPUT Initial Graph (n=5 cities) 0 1 2 3 4 Initial path: 0--1--2--3--4 Distance = 4 edges Query: [0, 3] 0 3 NEW ROAD n = 5 queries = [[0, 3]] Add road from city 0 directly to city 3 ALGORITHM STEPS Skip List Optimization 1 Initialize Skip List next[i] = i+1 for all cities next: [1, 2, 3, 4, -1] dist = 4 (count hops) 2 Process Query [0,3] Update: next[0] = 3 next: [3, 2, 3, 4, -1] 0 skips to 3 directly! 3 Remove Bypassed Cities 1,2 now bypassed Old: 0 -- 1 -- 2 -- 3 -- 4 New: 0 ------> 3 -- 4 4 Count Hops 0-->3-->4 = 2 edges Distance = 2 FINAL RESULT Optimized Graph 0 3 4 edge 1 edge 2 Cities 1, 2 bypassed 1 2 OUTPUT [2] Verification: Path: 0 --> 3 --> 4 Total edges = 2 [OK] Key Insight: Skip List Optimization allows O(1) shortcut updates. When adding road [u,v], we set next[u]=v and mark intermediate cities as bypassed. The constraint that queries don't overlap ensures no conflicts. Final distance = number of hops from city 0 to city n-1 following the skip pointers. TutorialsPoint - Shortest Distance After Road Addition Queries II | Skip List Optimization Approach
Asked in
Google 15 Meta 12 Amazon 8
8.5K Views
Medium Frequency
~35 min Avg. Time
245 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