You are given an integer n representing the number of nodes in a graph, labeled from 0 to n - 1. You are also given an integer array nums of length n and an integer maxDiff.

An undirected edge exists between nodes i and j if the absolute difference between nums[i] and nums[j] is at most maxDiff (i.e., |nums[i] - nums[j]| <= maxDiff).

You are also given a 2D integer array queries. For each queries[i] = [u_i, v_i], find the minimum distance between nodes u_i and v_i. If no path exists between the two nodes, return -1 for that query.

Return an array answer, where answer[i] is the result of the ith query.

Note: The edges between the nodes are unweighted.

Input & Output

Example 1 — Basic Path Query
$ Input: n = 4, nums = [1,3,5,7], maxDiff = 2, queries = [[0,3]]
Output: [3]
💡 Note: Nodes connected if |nums[i] - nums[j]| ≤ 2. Path: 0→1→2→3 (distance 3) since |1-3|≤2, |3-5|≤2, |5-7|≤2
Example 2 — No Path Exists
$ Input: n = 4, nums = [1,3,10,15], maxDiff = 2, queries = [[0,2]]
Output: [-1]
💡 Note: No path from node 0 to node 2. Nodes 0,1 connect (|1-3|≤2) but no connection to nodes 2,3 (|3-10|>2)
Example 3 — Multiple Queries
$ Input: n = 3, nums = [2,4,6], maxDiff = 3, queries = [[0,1],[0,2],[1,2]]
Output: [1,1,1]
💡 Note: All nodes connected: |2-4|≤3, |2-6|≤3, |4-6|≤3. Each query has direct path (distance 1)

Constraints

  • 2 ≤ n ≤ 104
  • nums.length == n
  • -109 ≤ nums[i] ≤ 109
  • 0 ≤ maxDiff ≤ 109
  • 1 ≤ queries.length ≤ 104
  • queries[i].length == 2
  • 0 ≤ ui, vi < n

Visualization

Tap to expand
Path Queries: Connect nodes by value similarity, find shortest distance0123nums[0]=1nums[1]=3nums[2]=5nums[3]=7|1-3|≤2|3-5|≤2|5-7|≤2BFS Level 1BFS Level 2BFS Level 3Query [0,3]: Shortest path distance = 3Path: 0 → 1 → 2 → 3 (3 edges)
Understanding the Visualization
1
Input
n=4 nodes with nums=[1,3,5,7], maxDiff=2, query=[0,3]
2
Build Graph
Connect nodes where |nums[i]-nums[j]| ≤ 2
3
BFS Search
Find shortest path from node 0 to node 3
Key Takeaway
🎯 Key Insight: Model as graph connectivity problem - BFS guarantees shortest unweighted path
Asked in
Google 35 Meta 28 Amazon 22
23.4K Views
Medium Frequency
~35 min Avg. Time
890 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