- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 51 lines of Java from the credited upstream file 1627.java.
- The implementation visibly relies on sequence storage.
- 4 loop blocks detected.
Complexity
Account for every find and union operation; with path compression and ranked merging, the amortized cost is nearly constant per operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class UnionFind {2 public UnionFind(int n) {3 id = new int[n];4 rank = new int[n];5 for (int i = 0; i < n; ++i)6 id[i] = i;7 }8 9 public boolean unionByRank(int u, int v) {10 final int i = find(u);11 final int j = find(v);12 if (i == j)13 return false;14 if (rank[i] < rank[j]) {15 id[i] = j;16 } else if (rank[i] > rank[j]) {17 id[j] = i;18 } else {19 id[i] = j;20 ++rank[j];21 }22 return true;23 }24 25 public int find(int u) {26 return id[u] == u ? u : (id[u] = find(id[u]));27 }28 29 private int[] id;30 private int[] rank;31}32 33class Solution {34 public List<Boolean> areConnected(int n, int threshold, int[][] queries) {35 List<Boolean> ans = new ArrayList<>();36 UnionFind uf = new UnionFind(n + 1);37 38 for (int z = threshold + 1; z <= n; ++z)39 for (int x = z * 2; x <= n; x += z)40 uf.unionByRank(z, x);41 42 for (int[] query : queries) {43 final int a = query[0];44 final int b = query[1];45 ans.add(uf.find(a) == uf.find(b));46 }47 48 return ans;49 }50}51