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 Existence Queries in a Graph II INPUT Graph Nodes (n=4) 0 nums[0]=1 1 nums[1]=3 2 nums[2]=5 3 nums[3]=7 Input Values: n = 4 nums = [1, 3, 5, 7] maxDiff = 2 queries = [[0, 3]] ALGORITHM STEPS 1 Sort by Values Sort nodes: 0,1,2,3 (vals: 1,3,5,7) 2 Build Edges |nums[i]-nums[j]| <= 2 Edges: 0-1, 1-2, 2-3 0 1 2 3 3 BFS from Node 0 Find shortest path to 3 4 Count Distance 0 --> 1 --> 2 --> 3 Distance = 3 hops FINAL RESULT Shortest Path Found: 0 1 1 1 2 1 3 Total Distance: 1 + 1 + 1 = 3 Output: [3] OK - Path exists Key Insight: By sorting nodes by their values, we can efficiently build edges between adjacent nodes whose difference is <= maxDiff. Then use BFS for shortest unweighted path queries. TutorialsPoint - Path Existence Queries in a Graph II | Optimized Graph Construction with Sorting
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