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.
Move from brute-force thinking to an efficient approach using array strategy.
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.
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 <= 5001 <= queries.length <= 500queries[i].length == 20 <= queries[i][0] < queries[i][1] < n1 < queries[i][1] - queries[i][0]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. 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
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 #3243: Shortest Distance After Road Addition Queries I
class Solution {
private List<Integer>[] g;
private int n;
public int[] shortestDistanceAfterQueries(int n, int[][] queries) {
this.n = n;
g = new List[n];
Arrays.setAll(g, i -> new ArrayList<>());
for (int i = 0; i < n - 1; ++i) {
g[i].add(i + 1);
}
int m = queries.length;
int[] ans = new int[m];
for (int i = 0; i < m; ++i) {
int u = queries[i][0], v = queries[i][1];
g[u].add(v);
ans[i] = bfs(0);
}
return ans;
}
private int bfs(int i) {
Deque<Integer> q = new ArrayDeque<>();
q.offer(i);
boolean[] vis = new boolean[n];
vis[i] = true;
for (int d = 0;; ++d) {
for (int k = q.size(); k > 0; --k) {
int u = q.poll();
if (u == n - 1) {
return d;
}
for (int v : g[u]) {
if (!vis[v]) {
vis[v] = true;
q.offer(v);
}
}
}
}
}
}
// Accepted solution for LeetCode #3243: Shortest Distance After Road Addition Queries I
func shortestDistanceAfterQueries(n int, queries [][]int) []int {
g := make([][]int, n)
for i := range g {
g[i] = append(g[i], i+1)
}
bfs := func(i int) int {
q := []int{i}
vis := make([]bool, n)
vis[i] = true
for d := 0; ; d++ {
for k := len(q); k > 0; k-- {
u := q[0]
if u == n-1 {
return d
}
q = q[1:]
for _, v := range g[u] {
if !vis[v] {
vis[v] = true
q = append(q, v)
}
}
}
}
}
ans := make([]int, len(queries))
for i, q := range queries {
g[q[0]] = append(g[q[0]], q[1])
ans[i] = bfs(0)
}
return ans
}
# Accepted solution for LeetCode #3243: Shortest Distance After Road Addition Queries I
class Solution:
def shortestDistanceAfterQueries(
self, n: int, queries: List[List[int]]
) -> List[int]:
def bfs(i: int) -> int:
q = deque([i])
vis = [False] * n
vis[i] = True
d = 0
while 1:
for _ in range(len(q)):
u = q.popleft()
if u == n - 1:
return d
for v in g[u]:
if not vis[v]:
vis[v] = True
q.append(v)
d += 1
g = [[i + 1] for i in range(n - 1)]
ans = []
for u, v in queries:
g[u].append(v)
ans.append(bfs(0))
return ans
// Accepted solution for LeetCode #3243: Shortest Distance After Road Addition Queries I
/**
* [3243] Shortest Distance After Road Addition Queries I
*/
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 matrix = vec![vec![]; n];
for i in 0..n - 1 {
matrix[i].push(i + 1);
}
let mut result = vec![];
for query in queries {
let (start, end) = (query[0] as usize, query[1] as usize);
matrix[start].push(end);
result.push(Self::bfs(n, &matrix));
}
result
}
fn bfs(n: usize, matrix: &Vec<Vec<usize>>) -> i32 {
use std::collections::VecDeque;
let mut distances = vec![-1; n];
let mut queue = VecDeque::new();
queue.push_back(0);
distances[0] = 0;
while let Some(head) = queue.pop_front() {
for &next in matrix[head].iter() {
if distances[next] >= 0 {
continue;
}
queue.push_back(next);
distances[next] = distances[head] + 1;
}
}
distances[n - 1]
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_3243() {
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 #3243: Shortest Distance After Road Addition Queries I
function shortestDistanceAfterQueries(n: number, queries: number[][]): number[] {
const g: number[][] = Array.from({ length: n }, () => []);
for (let i = 0; i < n - 1; ++i) {
g[i].push(i + 1);
}
const bfs = (i: number): number => {
const q: number[] = [i];
const vis: boolean[] = Array(n).fill(false);
vis[i] = true;
for (let d = 0; ; ++d) {
const nq: number[] = [];
for (const u of q) {
if (u === n - 1) {
return d;
}
for (const v of g[u]) {
if (!vis[v]) {
vis[v] = true;
nq.push(v);
}
}
}
q.splice(0, q.length, ...nq);
}
};
const ans: number[] = [];
for (const [u, v] of queries) {
g[u].push(v);
ans.push(bfs(0));
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
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.