class Solution { String[] copy; public int numSimilarGroups(String[] strs) { int n = strs.length; copy = strs; UnionFind uf = new UnionFind(n); for(int i =0;i < n-1;i++){ for(int j = i+1;j<n;j++){ if(isSimilar(strs[i],strs[j]) == true) uf.union(i,j); } } return uf.getCount(); } public boolean isSimilar(String str1,String str2) { int num = 0; for (int i = 0; i < str1.length(); i++) { if (str1.charAt(i) != str2.charAt(i)) { num++; if (num > 2) { return false; } } } return true; } public class UnionFind{ int[] parent; int[] rank; int count; public int getCount(){ return count; } public UnionFind(int n){ parent = new int[n]; rank = new int[n]; count = n; for(int i = 0;i < n;i++){ parent[i] = i; rank[i] = 1; } } public int find(int x){ if(parent[x] != x){ parent[x] = find(parent[x]); } return parent[x]; } public void union(int x,int y){ int rootX = find(x); int rootY = find(y); if(rootX == rootY) return ; if(rank[rootX] == rank[rootY]){ parent[rootX] = rootY; rank[rootY] += 1; } else if(rank[rootX] > rank[rootY]){ parent[rootY] = rootX; } else{ parent[rootX] = rootY; } count -= 1; } } }