- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 64 lines of C++ from the credited upstream file 721.cpp.
- 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:3 UnionFind(int 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 }20 21 int find(int u) {22 return id[u] == u ? u : id[u] = find(id[u]);23 }24 25 private:26 vector<int> id;27 vector<int> sz;28};29 30class Solution {31 public:32 vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {33 vector<vector<string>> ans;34 unordered_map<string, int> emailToIndex; 35 unordered_map<int, set<string>> indexToEmails; 36 UnionFind uf(accounts.size());37 38 for (int i = 0; i < accounts.size(); ++i) {39 const string name = accounts[i][0];40 for (int j = 1; j < accounts[i].size(); ++j) {41 const string email = accounts[i][j];42 const auto it = emailToIndex.find(email);43 if (it == emailToIndex.end()) {44 emailToIndex[email] = i;45 } else {46 uf.unionBySize(i, it->second);47 }48 }49 }50 51 for (const auto& [email, index] : emailToIndex)52 indexToEmails[uf.find(index)].insert(email);53 54 for (const auto& [index, emails] : indexToEmails) {55 const string name = accounts[index][0];56 vector<string> row{name};57 row.insert(row.end(), emails.begin(), emails.end());58 ans.push_back(row);59 }60 61 return ans;62 }63};64