Accounts Merge
Pattern: Disjoint set union
Accounts that share any email belong to the same person. Union accounts that share an email (remember the first account each email appeared in), then collect each group's emails, sorted, under the group's name.
The problem
Each account is [name, email, email, ...]. Two accounts belong to the same person if they share an email (people with
the same name may be different people). Return the merged accounts, each as [name, sorted emails...]. The tests sort
the accounts.
Think first
- What makes two accounts the same person?
- Can the name decide?
- How do you avoid comparing every pair of accounts?
Hints
Brute force, and why it fails
Compare every pair of accounts: O(A² × E).
The key insight
Shared emails define edges between accounts, so union-find groups them in one pass over the emails.
Dry run
Accounts: John [a, b], John [a, c], Mary [m], John [d]. The first two share a.
The plan
owner = {}; for account i: for email: if in owner: union(i, owner[email]) else owner[email] = i
collect emails per root; sort
Complexity
- Time
O(N log N)- Space
O(N)
N is the total number of emails; sorting each group dominates.
Edge cases
- One account.
- Same name, no shared email: kept apart.
- A chain of shared emails across three accounts.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<List<String>> accountsMerge(String[][] accounts) {
int n = accounts.length;
int[] parent = new int[n];
for (int i = 0; i < n; i++) parent[i] = i;
Map<String, Integer> owner = new HashMap<>(); // email -> the first account that has it
for (int i = 0; i < n; i++)
for (int k = 1; k < accounts[i].length; k++) {
Integer j = owner.putIfAbsent(accounts[i][k], i);
if (j != null) parent[find(parent, i)] = find(parent, j); // a shared email: same person
}
Map<Integer, TreeSet<String>> groups = new HashMap<>();
for (int i = 0; i < n; i++)
for (int k = 1; k < accounts[i].length; k++) groups.computeIfAbsent(find(parent, i), x -> new TreeSet<>()).add(accounts[i][k]);
List<List<String>> out = new ArrayList<>();
for (Map.Entry<Integer, TreeSet<String>> g : groups.entrySet()) {
List<String> acc = new ArrayList<>();
acc.add(accounts[g.getKey()][0]); // the name, then the emails in order
acc.addAll(g.getValue());
out.add(acc);
}
return out;
}
private int find(int[] parent, int x) {
while (parent[x] != x) x = parent[x] = parent[parent[x]];
return x;
}
}C++
class Solution {
public:
vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {
int n = static_cast<int>(accounts.size());
vector<int> parent(n);
for (int i = 0; i < n; i++) parent[i] = i;
unordered_map<string, int> owner; // email -> the first account that has it
for (int i = 0; i < n; i++)
for (size_t k = 1; k < accounts[i].size(); k++) {
auto it = owner.find(accounts[i][k]);
if (it == owner.end()) owner[accounts[i][k]] = i;
else parent[find(parent, i)] = find(parent, it->second); // a shared email: same person
}
map<int, set<string>> groups;
for (int i = 0; i < n; i++)
for (size_t k = 1; k < accounts[i].size(); k++) groups[find(parent, i)].insert(accounts[i][k]);
vector<vector<string>> out;
for (auto& g : groups) {
vector<string> acc(1, accounts[g.first][0]); // the name, then the emails in order
acc.insert(acc.end(), g.second.begin(), g.second.end());
out.push_back(acc);
}
return out;
}
int find(vector<int>& parent, int x) {
while (parent[x] != x) x = parent[x] = parent[parent[x]];
return x;
}
};Python
class Solution:
def accountsMerge(self, accounts: list[list[str]]) -> list[list[str]]:
parent = list(range(len(accounts)))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
owner = {} # email -> the first account that has it
for i, acc in enumerate(accounts):
for email in acc[1:]:
if email in owner:
parent[find(i)] = find(owner[email]) # a shared email: same person
else:
owner[email] = i
groups = {}
for i, acc in enumerate(accounts):
groups.setdefault(find(i), set()).update(acc[1:])
return [[accounts[root][0]] + sorted(emails) for root, emails in groups.items()] # name, then emailsCommon mistakes
- Merging by name.
- Forgetting to sort emails.