Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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.
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.
Example 1:
Input: n = 5, queries = [[2,4],[0,2],[0,4]]
Output: [3,2,1]
Explanation:
After the addition of the road from 2 to 4, the length of the shortest path from 0 to 4 is 3.
After the addition of the road from 0 to 2, the length of the shortest path from 0 to 4 is 2.
After the addition of the road from 0 to 4, the length of the shortest path from 0 to 4 is 1.
Example 2:
Input: n = 4, queries = [[0,3],[0,2]]
Output: [1,1]
Explanation:
After the addition of the road from 0 to 3, the length of the shortest path from 0 to 3 is 1.
After the addition of the road from 0 to 2, the length of the shortest path remains 1.
Constraints:
3 <= n <= 1051 <= queries.length <= 105queries[i].length == 20 <= queries[i][0] < queries[i][1] < n1 < queries[i][1] - queries[i][0]i != j and queries[i][0] < queries[j][0] < queries[i][1] < queries[j][1].Problem summary: 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. 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Greedy · Segment Tree
5 [[2,4],[0,2],[0,4]]
4 [[0,3],[0,2]]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3244: Shortest Distance After Road Addition Queries II
class Solution {
public int[] shortestDistanceAfterQueries(int n, int[][] queries) {
int[] nxt = new int[n - 1];
for (int i = 1; i < n; ++i) {
nxt[i - 1] = i;
}
int m = queries.length;
int cnt = n - 1;
int[] ans = new int[m];
for (int i = 0; i < m; ++i) {
int u = queries[i][0], v = queries[i][1];
if (nxt[u] > 0 && nxt[u] < v) {
int j = nxt[u];
while (j < v) {
--cnt;
int t = nxt[j];
nxt[j] = 0;
j = t;
}
nxt[u] = v;
}
ans[i] = cnt;
}
return ans;
}
}
// Accepted solution for LeetCode #3244: Shortest Distance After Road Addition Queries II
func shortestDistanceAfterQueries(n int, queries [][]int) (ans []int) {
nxt := make([]int, n-1)
for i := range nxt {
nxt[i] = i + 1
}
cnt := n - 1
for _, q := range queries {
u, v := q[0], q[1]
if nxt[u] > 0 && nxt[u] < v {
i := nxt[u]
for i < v {
cnt--
nxt[i], i = 0, nxt[i]
}
nxt[u] = v
}
ans = append(ans, cnt)
}
return
}
# Accepted solution for LeetCode #3244: Shortest Distance After Road Addition Queries II
class Solution:
def shortestDistanceAfterQueries(
self, n: int, queries: List[List[int]]
) -> List[int]:
nxt = list(range(1, n))
ans = []
cnt = n - 1
for u, v in queries:
if 0 < nxt[u] < v:
i = nxt[u]
while i < v:
cnt -= 1
nxt[i], i = 0, nxt[i]
nxt[u] = v
ans.append(cnt)
return ans
// Accepted solution for LeetCode #3244: Shortest Distance After Road Addition Queries II
/**
* [3244] Shortest Distance After Road Addition Queries II
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn shortest_distance_after_queries(n: i32, queries: Vec<Vec<i32>>) -> Vec<i32> {
let n = n as usize;
let mut roads = vec![None; n];
for i in 0..n {
roads[i] = Some(i + 1);
}
let mut result = Vec::with_capacity(queries.len());
let mut distance = n - 1;
for query in queries {
let (start, end) = (query[0] as usize, query[1] as usize);
let mut k = roads[start];
roads[start] = Some(end);
while let Some(now) = k {
if now >= end {
break;
}
k = roads[now];
roads[now] = None;
distance -= 1;
}
result.push(distance);
}
result.into_iter().map(|x| x as i32).collect()
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_3244() {
assert_eq!(
vec![3, 2, 1],
Solution::shortest_distance_after_queries(5, vec![vec![2, 4], vec![0, 2], vec![0, 4]])
);
assert_eq!(
vec![1, 1],
Solution::shortest_distance_after_queries(4, vec![vec![0, 3], vec![0, 2]])
);
}
}
// Accepted solution for LeetCode #3244: Shortest Distance After Road Addition Queries II
function shortestDistanceAfterQueries(n: number, queries: number[][]): number[] {
const nxt: number[] = Array.from({ length: n - 1 }, (_, i) => i + 1);
const ans: number[] = [];
let cnt = n - 1;
for (const [u, v] of queries) {
if (nxt[u] && nxt[u] < v) {
let i = nxt[u];
while (i < v) {
--cnt;
[nxt[i], i] = [0, nxt[i]];
}
nxt[u] = v;
}
ans.push(cnt);
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.