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