Problem solution · C++

Accounts Merge

Accounts Merge: a C++ solution using disjoint set union. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Disjoint set union
Source
walkccc LeetCode Solutions
Length
64 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Disjoint set union

For Accounts Merge, the implementation maintains connected components and merges them as relationships are processed.

  1. Give each element a component representative.
  2. Merge representatives when a connection is accepted.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeAccounts Merge · C++C++
Use this to learn the idea, then write your own version.
class UnionFind { public:  UnionFind(int n) : id(n), sz(n, 1) {    iota(id.begin(), id.end(), 0);  }   void unionBySize(int u, int v) {    const int i = find(u);    const int j = find(v);    if (i == j)      return;    if (sz[i] < sz[j]) {      sz[j] += sz[i];      id[i] = j;    } else {      sz[i] += sz[j];      id[j] = i;    }  }   int find(int u) {    return id[u] == u ? u : id[u] = find(id[u]);  }  private:  vector<int> id;  vector<int> sz;}; class Solution { public:  vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {    vector<vector<string>> ans;    unordered_map<string, int> emailToIndex;        // {email: index}    unordered_map<int, set<string>> indexToEmails;  // {index: {emails}}    UnionFind uf(accounts.size());     for (int i = 0; i < accounts.size(); ++i) {      const string name = accounts[i][0];      for (int j = 1; j < accounts[i].size(); ++j) {        const string email = accounts[i][j];        const auto it = emailToIndex.find(email);        if (it == emailToIndex.end()) {          emailToIndex[email] = i;        } else {          uf.unionBySize(i, it->second);        }      }    }     for (const auto& [email, index] : emailToIndex)      indexToEmails[uf.find(index)].insert(email);     for (const auto& [index, emails] : indexToEmails) {      const string name = accounts[index][0];      vector<string> row{name};      row.insert(row.end(), emails.begin(), emails.end());      ans.push_back(row);    }     return ans;  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗