- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 82 lines of Java from the credited upstream file 2709.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 10 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 sz = new int[n];5 for (int i = 0; i < n; ++i)6 id[i] = i;7 for (int i = 0; i < n; ++i)8 sz[i] = 1;9 }10 11 public void unionBySize(int u, int v) {12 final int i = find(u);13 final int j = find(v);14 if (i == j)15 return;16 if (sz[i] < sz[j]) {17 sz[j] += sz[i];18 id[i] = j;19 } else {20 sz[i] += sz[j];21 id[j] = i;22 }23 }24 25 public int getSize(int i) {26 return sz[i];27 }28 29 private int[] id;30 private int[] sz;31 32 private int find(int u) {33 return id[u] == u ? u : (id[u] = find(id[u]));34 }35}36 37class Solution {38 public boolean canTraverseAllPairs(int[] nums) {39 final int n = nums.length;40 final int mx = Arrays.stream(nums).max().getAsInt();41 final int[] minPrimeFactors = sieveEratosthenes(mx + 1);42 Map<Integer, Integer> primeToFirstIndex = new HashMap<>();43 UnionFind uf = new UnionFind(n);44 45 for (int i = 0; i < n; ++i)46 for (final int primeFactor : getPrimeFactors(nums[i], minPrimeFactors))47 48 if (primeToFirstIndex.containsKey(primeFactor))49 uf.unionBySize(primeToFirstIndex.get(primeFactor), i);50 else51 primeToFirstIndex.put(primeFactor, i);52 53 for (int i = 0; i < n; ++i)54 if (uf.getSize(i) == n)55 return true;56 return false;57 }58 59 60 private int[] sieveEratosthenes(int n) {61 int[] minPrimeFactors = new int[n + 1];62 for (int i = 2; i <= n; ++i)63 minPrimeFactors[i] = i;64 for (int i = 2; i * i < n; ++i)65 if (minPrimeFactors[i] == i) 66 for (int j = i * i; j < n; j += i)67 minPrimeFactors[j] = Math.min(minPrimeFactors[j], i);68 return minPrimeFactors;69 }70 71 private List<Integer> getPrimeFactors(int num, int[] minPrimeFactors) {72 List<Integer> primeFactors = new ArrayList<>();73 while (num > 1) {74 final int divisor = minPrimeFactors[num];75 primeFactors.add(divisor);76 while (num % divisor == 0)77 num /= divisor;78 }79 return primeFactors;80 }81}82