The Graph Connectivity With Threshold interview question asks you to determine if there is a path between various pairs of nodes in a graph. The graph consists of nodes numbered from to . Two nodes and share an undirected edge if and only if they share a common divisor strictly greater than a given threshold. You are given an array of queries [u, v], and for each query, you must return a boolean indicating if and are connected.
Uber asks this Hard difficulty Math and Graph problem to test a candidate's mastery of the Union Find (Disjoint Set) data structure combined with Number Theory. A brute-force approach (checking the GCD of every possible pair to build the graph) takes , which is too slow. It evaluates if you can use the Sieve of Eratosthenes concept to build the graph connections in time.
This problem uses Union Find with Multiples (Sieve Pattern).
threshold + 1 up to .union(z, 2z), union(2z, 3z)).find(u) == find(v).n = 6, threshold = 2.
union(3, 6). (Nodes 3 and 6 are now connected).[3, 6], they have the same root. Return True.
If a query asks [1, 5], they have different roots. Return False.gcd(i, j) > threshold for every pair . This results in a Time Limit Exceeded (TLE) error.find operations.threshold instead of threshold + 1.Whenever a problem involves connecting numbers based on common divisors, immediately think of iterating over divisors and grouping their multiples. It's the most efficient way to build such "math-based" graphs.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Greatest Common Divisor Traversal | Hard | Solve | |
| GCD Sort of an Array | Hard | Solve | |
| Largest Component Size by Common Factor | Hard | Solve | |
| Check If It Is a Good Array | Hard | Solve | |
| Count Array Pairs Divisible by K | Hard | Solve |