Path Existence Queries in a Graph II - Problem
Path Existence Queries in a Graph II
Imagine you're building a social network where people are connected based on how similar their interests are! š
You're given
Your task: For each query
Input:
ā¢
ā¢
ā¢
ā¢
Output: Array of shortest distances for each query
Imagine you're building a social network where people are connected based on how similar their interests are! š
You're given
n people (nodes 0 to n-1) in a network, where each person has an interest score stored in array nums. Two people are connected (have an edge between them) if their interest scores are similar enough - specifically, if the absolute difference between their scores is at most maxDiff.Your task: For each query
[u, v], find the shortest path (minimum number of connections) between person u and person v. If they can't be connected through any chain of friendships, return -1.Input:
ā¢
n: number of peopleā¢
nums: array of interest scoresā¢
maxDiff: maximum allowed difference for connectionā¢
queries: pairs of people to checkOutput: Array of shortest distances for each query
Input & Output
example_1.py ā Basic Example
$
Input:
n = 4, nums = [1, 3, 5, 2], maxDiff = 2, queries = [[0, 3], [1, 2], [0, 2]]
āŗ
Output:
[1, 1, 2]
š” Note:
Graph edges: 0-1 (|1-3|=2ā¤2), 1-2 (|3-5|=2ā¤2), 0-3 (|1-2|=1ā¤2). Query [0,3]: direct connection, distance=1. Query [1,2]: direct connection, distance=1. Query [0,2]: path 0ā1ā2, distance=2.
example_2.py ā Disconnected Components
$
Input:
n = 4, nums = [1, 5, 10, 6], maxDiff = 3, queries = [[0, 2], [1, 3]]
āŗ
Output:
[-1, 1]
š” Note:
Graph edges: 1-3 (|5-6|=1ā¤3). Node 0 (val=1) and node 2 (val=10) are in separate components, so distance=-1. Nodes 1 and 3 are directly connected, distance=1.
example_3.py ā Self Query
$
Input:
n = 3, nums = [2, 4, 6], maxDiff = 1, queries = [[0, 0], [1, 2]]
āŗ
Output:
[0, -1]
š” Note:
No edges exist since all differences > 1. Query [0,0]: same node, distance=0. Query [1,2]: no path exists since |4-6|=2>1, distance=-1.
Constraints
- 2 ⤠n ⤠300
- 1 ⤠nums.length = n
- 1 ⤠nums[i] ⤠106
- 0 ⤠maxDiff ⤠106
- 1 ⤠queries.length ⤠105
- queries[i] = [ui, vi] where 0 ⤠ui, vi < n
Visualization
Tap to expand
Understanding the Visualization
1
Create Connections
Connect people whose interest scores differ by at most maxDiff
2
Find Shortest Path
Use BFS to find the minimum number of connections between two people
3
Handle Queries
Answer multiple queries efficiently using the prebuilt network
Key Takeaway
šÆ Key Insight: Build the graph once during preprocessing, then use BFS for efficient shortest path queries. This transforms an O(QĆn²) problem into O(n² + QĆn) by avoiding repeated graph construction.
š”
Explanation
AI Ready
š” Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code