#1627
Graph Connectivity With Threshold
HardArrayMathUnion-FindNumber TheoryUnion-FindGraph Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
We can use a Union-Find (Disjoint Set Union) structure to efficiently group cities based on their connections. By connecting cities that share common divisors greater than the threshold, we can quickly answer the queries.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a Union-Find structure for n cities.
- 2Step 2: For each integer from threshold + 1 to n, connect all multiples of that integer.
- 3Step 3: For each query, check if the two cities belong to the same connected component in the Union-Find structure.
solution.py29 lines
1# Full working Python code
2class UnionFind:
3 def __init__(self, size):
4 self.parent = list(range(size))
5
6 def find(self, x):
7 if self.parent[x] != x:
8 self.parent[x] = self.find(self.parent[x])
9 return self.parent[x]
10
11 def union(self, x, y):
12 rootX = self.find(x)
13 rootY = self.find(y)
14 if rootX != rootY:
15 self.parent[rootY] = rootX
16
17
18def are_connected(n, threshold, queries):
19 uf = UnionFind(n + 1)
20 for z in range(threshold + 1, n + 1):
21 for multiple in range(2 * z, n + 1, z):
22 uf.union(z, multiple)
23 results = []
24 for a, b in queries:
25 results.append(uf.find(a) == uf.find(b))
26 return results
27
28# Example usage
29print(are_connected(6, 2, [[1,4],[2,5],[3,6]]))ℹ
Complexity note: The complexity is due to the union-find operations and the number of multiples we process, which is efficient compared to the brute force approach.
- 1Cities can be connected through common divisors, which can be efficiently managed using Union-Find.
- 2Understanding the properties of divisors helps in optimizing the connection process.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.