Graph Connectivity With Threshold - Problem
You have n cities labeled from 1 to n. Two different cities with labels x and y are directly connected by a bidirectional road if and only if x and y share a common divisor strictly greater than some threshold.
More formally, cities with labels x and y have a road between them if there exists an integer z such that:
x % z == 0y % z == 0z > threshold
Given the integers n and threshold, and an array of queries, determine for each queries[i] = [ai, bi] if cities ai and bi are connected directly or indirectly.
Return an array answer, where answer[i] is true if there is a path between ai and bi, or false if no path exists.
Input & Output
Example 1 — Basic Connectivity
$
Input:
n = 6, threshold = 2, queries = [[1,4],[4,5],[3,6]]
›
Output:
[false,false,true]
💡 Note:
With threshold=2, cities are connected if they share divisor > 2. City 3 and 6 share divisor 3 > 2, so they're connected. Cities 1,4 and 4,5 don't share divisors > 2.
Example 2 — Lower Threshold
$
Input:
n = 6, threshold = 0, queries = [[4,5],[4,6],[3,6]]
›
Output:
[false,true,true]
💡 Note:
With threshold=0, cities need common divisor > 0. Cities 4,6 share divisor 2 > 0 (connected). Cities 3,6 share divisor 3 > 0 (connected). Cities 4,5 share only divisor 1, which is not > 0.
Example 3 — No Connections
$
Input:
n = 5, threshold = 4, queries = [[2,3],[1,5]]
›
Output:
[false,false]
💡 Note:
With high threshold=4, no cities can be connected since largest city is 5 and no pairs share divisor > 4.
Constraints
- 1 ≤ n ≤ 104
- 0 ≤ threshold ≤ n
- 1 ≤ queries.length ≤ 105
- queries[i].length == 2
- 1 ≤ ai, bi ≤ cities
Visualization
Tap to expand
Understanding the Visualization
1
Input
Cities 1-6, threshold=2, queries about connectivity
2
Process
Build connections where cities share divisor > 2
3
Output
Array of boolean answers for each query
Key Takeaway
🎯 Key Insight: Use Union-Find to precompute connected components by grouping cities that share divisors > threshold
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code