Path Existence Queries in a Graph I - Problem

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 sorted in non-decreasing order, 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], determine whether there exists a path between nodes u_i and v_i.

Return a boolean array answer, where answer[i] is true if there exists a path between u_i and v_i in the i-th query and false otherwise.

Input & Output

Example 1 — Basic Path Queries
$ Input: n = 4, nums = [4,4,2,3], maxDiff = 1, queries = [[2,3],[0,3]]
Output: [true,false]
💡 Note: Edges exist between nodes with |nums[i] - nums[j]| ≤ 1. Node 0↔1 (|4-4|=0≤1), Node 2↔3 (|2-3|=1≤1). Query [2,3] is connected, [0,3] is not.
Example 2 — All Connected
$ Input: n = 3, nums = [1,2,3], maxDiff = 2, queries = [[0,1],[1,2],[0,2]]
Output: [true,true,true]
💡 Note: All pairs have difference ≤ 2: |1-2|=1, |1-3|=2, |2-3|=1. All nodes are connected, so all queries return true.
Example 3 — No Connections
$ Input: n = 2, nums = [1,5], maxDiff = 3, queries = [[0,1]]
Output: [false]
💡 Note: |1-5| = 4 > 3, so no edge exists between nodes 0 and 1. They are not connected.

Constraints

  • 2 ≤ n ≤ 104
  • nums.length == n
  • 1 ≤ nums[i] ≤ 109
  • nums is sorted in non-decreasing order
  • 0 ≤ maxDiff ≤ 109
  • 1 ≤ queries.length ≤ 104
  • queries[i].length == 2
  • 0 ≤ ui, vi < n

Visualization

Tap to expand
Path Existence Queries: Build Graph and Check ConnectivityInput: nums = [4,4,2,3], maxDiff = 10123val=4val=4val=2val=3|4-4|=0≤1|2-3|=1≤1Connected Components:Group 1: {0,1}Group 2: {2,3}Query Processing:Query [2,3]: Both in Group 2 → trueQuery [0,3]: Different groups → falseOutput: [true, false]
Understanding the Visualization
1
Input Graph
Nodes with values, edges where |nums[i] - nums[j]| ≤ maxDiff
2
Connected Components
Group nodes that can reach each other
3
Query Results
Check if query nodes are in same component
Key Takeaway
🎯 Key Insight: Precompute connected components using Union-Find for efficient query answering
Asked in
Google 25 Amazon 18 Microsoft 15
23.4K Views
Medium Frequency
~25 min Avg. Time
892 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