Skip to main content
LeetCode 3243, Medium. Topics: Array, Breadth-First Search, Graph Theory. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 22 parametrized pytest cases, and a playground notebook:

Problem

You are given an integer <code>n</code> and a 2D integer array <code>queries</code>. There are <code>n</code> cities numbered from <code>0</code> to <code>n - 1</code>. Initially, there is a <strong>unidirectional</strong> road from city <code>i</code> to city <code>i + 1</code> for all <code>0 <= i < n - 1</code>. <code>queries[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> represents the addition of a new <strong>unidirectional</strong> road from city <code>u<sub>i</sub></code> to city <code>v<sub>i</sub></code>. After each query, you need to find the <strong>length</strong> of the <strong>shortest path</strong> from city <code>0</code> to city <code>n - 1</code>. Return an array <code>answer</code> where for each <code>i</code> in the range <code>[0, queries.length - 1]</code>, <code>answer[i]</code> is the length of the shortest path from city <code>0</code> to city <code>n - 1</code> after processing the <strong>first</strong> <code>i + 1</code> queries.

Examples

Example 1
Example 1 After the addition of the road from 0 to 2, the length of the shortest path from 0 to 4 is 2. Example 1 After the addition of the road from 0 to 4, the length of the shortest path from 0 to 4 is 1. Example 2
Example 2 After the addition of the road from 0 to 2, the length of the shortest path remains 1.

Constraints

  • <code>3 <= n <= 500</code>
  • <code>1 <= queries.length <= 500</code>
  • <code>queries[i].length == 2</code>
  • <code>0 <= queries[i][0] < queries[i][1] < n</code>
  • <code>1 < queries[i][1] - queries[i][0]</code>
  • There are no repeated roads among the queries.

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026