- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 52 lines of Java from the credited upstream file 952.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 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 void unionByRank(int u, int v) {10 final int i = find(u);11 final int j = find(v);12 if (i == j)13 return;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 }23 24 public int find(int u) {25 return id[u] == u ? u : (id[u] = find(id[u]));26 }27 28 private int[] id;29 private int[] rank;30}31 32class Solution {33 public int largestComponentSize(int[] nums) {34 final int n = Arrays.stream(nums).max().getAsInt();35 int ans = 0;36 UnionFind uf = new UnionFind(n + 1);37 Map<Integer, Integer> count = new HashMap<>();38 39 for (final int num : nums)40 for (int x = 2; x <= (int) Math.sqrt(num); ++x)41 if (num % x == 0) {42 uf.unionByRank(num, x);43 uf.unionByRank(num, num / x);44 }45 46 for (final int num : nums)47 ans = Math.max(ans, count.merge(uf.find(num), 1, Integer::sum));48 49 return ans;50 }51}52