1. Iterative Pairwise Merging
Intuition
Iteratively compare pairs of accounts. If two accounts share at least one email, merge their emails into one account and remove the other. Repeat until a full pass makes zero merges.
Algorithm
- Convert each account's emails into a set.
- Loop with a
mergedflag: for every pair (i, j), check if their email sets have a non-empty intersection. - If they intersect, union account j's emails into account i, remove account j, and set merged = true.
- Repeat until a complete pass occurs without any merges.
- Sort the emails for each merged account and attach the name.
#include <iostream>#include <vector>#include <string>#include <unordered_set>#include <algorithm> using namespace std; class Solution {public: vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) { vector<pair<string, unordered_set<string>>> accList; for (const auto& acc : accounts) { unordered_set<string> emails(acc.begin() + 1, acc.end()); accList.push_back({acc[0], emails}); } bool merged = true; while (merged) { merged = false; for (size_t i = 0; i < accList.size(); ++i) { for (size_t j = i + 1; j < accList.size(); ++j) { if (accList[i].first != accList[j].first) continue; bool overlap = false; for (const auto& email : accList[j].second) { if (accList[i].second.count(email)) { overlap = true; break; } } if (overlap) { accList[i].second.insert(accList[j].second.begin(), accList[j].second.end()); accList.erase(accList.begin() + j); merged = true; break; } } if (merged) break; } } vector<vector<string>> result; for (auto& p : accList) { vector<string> emails(p.second.begin(), p.second.end()); sort(emails.begin(), emails.end()); emails.insert(emails.begin(), p.first); result.push_back(emails); } return result; }}; int main() { Solution solver; vector<vector<string>> accounts = { {"John","johnsmith@mail.com","john_newyork@mail.com"}, {"John","johnsmith@mail.com","john00@mail.com"}, {"Mary","mary@mail.com"}, {"John","johnnybravo@mail.com"} }; auto res = solver.accountsMerge(accounts); for (const auto& acc : res) { cout << acc[0] << ": "; for (size_t i = 1; i < acc.size(); ++i) cout << acc[i] << " "; cout << endl; } return 0;}Time & Space Complexity
- Time complexity:
O(N^2 * K^2) - Space complexity:
O(N * K)