- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 42 lines of Java from the credited upstream file 3378.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 2 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 void unionByRank(int u, int v) {3 final int i = find(u);4 final int j = find(v);5 if (i == j)6 return;7 if (rank.get(i) < rank.get(j)) {8 id.put(i, j);9 } else if (rank.get(i) > rank.get(j)) {10 id.put(j, i);11 } else {12 id.put(i, j);13 rank.merge(j, 1, Integer::sum);14 }15 }16 17 public int find(int u) {18 if (!id.containsKey(u)) {19 id.put(u, u);20 rank.put(u, 0);21 }22 if (id.get(u) != u)23 id.put(u, find(id.get(u)));24 return id.get(u);25 }26 27 private Map<Integer, Integer> id = new HashMap<>();28 private Map<Integer, Integer> rank = new HashMap<>();29}30 31class Solution {32 public int countComponents(int[] nums, int threshold) {33 UnionFind uf = new UnionFind();34 35 for (final int num : nums)36 for (int multiple = 2 * num; multiple <= threshold; multiple += num)37 uf.unionByRank(num, multiple);38 39 return Arrays.stream(nums).map(uf::find).boxed().collect(Collectors.toSet()).size();40 }41}42