- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 81 lines of Java from the credited upstream file 2157.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 5 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 count = n;4 id = new int[n];5 sz = new int[n];6 for (int i = 0; i < n; ++i)7 id[i] = i;8 for (int i = 0; i < n; ++i)9 sz[i] = 1;10 }11 12 public void unionBySize(int u, int v) {13 final int i = find(u);14 final int j = find(v);15 if (i == j)16 return;17 if (sz[i] < sz[j]) {18 sz[j] += sz[i];19 id[i] = j;20 } else {21 sz[i] += sz[j];22 id[j] = i;23 }24 --count;25 }26 27 public int getCount() {28 return count;29 }30 31 public int getMaxSize() {32 return Arrays.stream(sz).max().getAsInt();33 }34 35 private int count;36 private int[] id;37 private int[] sz;38 39 private int find(int u) {40 return id[u] == u ? u : (id[u] = find(id[u]));41 }42}43 44class Solution {45 public int[] groupStrings(String[] words) {46 UnionFind uf = new UnionFind(words.length);47 Map<Integer, Integer> maskToIndex = new HashMap<>();48 Map<Integer, Integer> deletedMaskToIndex = new HashMap<>();49 50 for (int i = 0; i < words.length; ++i) {51 final int mask = getMask(words[i]);52 for (int j = 0; j < 26; ++j)53 if ((mask >> j & 1) == 1) {54 55 final int m = mask ^ 1 << j;56 if (maskToIndex.containsKey(m))57 uf.unionBySize(i, maskToIndex.get(m));58 if (deletedMaskToIndex.containsKey(m))59 uf.unionBySize(i, deletedMaskToIndex.get(m));60 else61 deletedMaskToIndex.put(m, i);62 } else {63 64 final int m = mask | 1 << j;65 if (maskToIndex.containsKey(m))66 uf.unionBySize(i, maskToIndex.get(m));67 }68 maskToIndex.put(mask, i);69 }70 71 return new int[] {uf.getCount(), uf.getMaxSize()};72 }73 74 private int getMask(final String s) {75 int mask = 0;76 for (final char c : s.toCharArray())77 mask |= 1 << c - 'a';78 return mask;79 }80}81