Algo-Sim › Advanced Graphs
Accounts Merge
Medium · Advanced Graphs · step through it in Java, Python and C++ on your own input
Union every pair of accounts that share an email; each union-find root is one person, whose emails are gathered and sorted.
Problem
Each account is a name followed by emails. Two accounts belong to the same person when they share at least one email (people with the same name can still be different). Merge each person’s accounts into one: the name, then all their emails in sorted order. Return the merged accounts in any order; here they are listed by the account that ends up as the root.
Constraints
- 1 ≤ accounts.length ≤ 1000
- 2 ≤ accounts[i].length ≤ 10
- An email belongs to one person
Edge cases to test
- Two accounts with the same name but no shared email (different people)
- One account
- A chain of shared emails joining three accounts
Follow-up questions
- Why union accounts, not emails?
- Either works; mapping each email to its first account and unioning accounts keeps the sets small.
- What is the cost?
- O(E α(E)) for E emails, plus O(E log E) to sort each group’s emails.
Solution
Java
public List<List<String>> accountsMerge(List<List<String>> accounts) {
int n = accounts.size();
int[] parent = new int[n];
for (int i = 0; i < n; i++) parent[i] = i;
Map<String, Integer> owner = new HashMap<>(); // email → first account
for (int i = 0; i < n; i++) {
for (String email : accounts.get(i).subList(1, accounts.get(i).size())) {
if (owner.containsKey(email)) {
int ra = find(parent, i), rb = find(parent, owner.get(email));
parent[ra] = rb;
} else {
owner.put(email, i);
}
}
}
Map<Integer, TreeSet<String>> groups = new HashMap<>();
for (Map.Entry<String, Integer> e : owner.entrySet()) {
groups.computeIfAbsent(find(parent, e.getValue()), k -> new TreeSet<>()).add(e.getKey());
}
List<List<String>> merged = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (!groups.containsKey(i)) continue;
List<String> account = new ArrayList<>(List.of(accounts.get(i).get(0)));
account.addAll(groups.get(i)); // sorted by the TreeSet
merged.add(account);
}
return merged;
}
private int find(int[] parent, int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}Python
from collections import defaultdict
def accounts_merge(accounts):
parent = list(range(len(accounts)))
owner = {} # email → first account
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for i, account in enumerate(accounts):
for email in account[1:]:
if email in owner:
ra, rb = find(i), find(owner[email])
parent[ra] = rb
else:
owner[email] = i
groups = defaultdict(list)
for email, i in owner.items():
groups[find(i)].append(email)
merged = []
for i in range(len(accounts)):
if i in groups:
merged.append([accounts[i][0]] + sorted(groups[i]))
return mergedC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<string>> accountsMerge(vector<vector<string>> &accounts) {
int n = int(accounts.size());
vector<int> parent(n);
iota(parent.begin(), parent.end(), 0);
map<string, int> owner;
for (int i = 0; i < n; i++) {
for (int k = 1; k < int(accounts[i].size()); k++) {
const string &email = accounts[i][k];
if (owner.count(email)) {
int ra = find(parent, i), rb = find(parent, owner[email]);
parent[ra] = rb;
} else {
owner[email] = i;
}
}
}
map<int, vector<string>> groups;
for (auto &[email, i] : owner)
groups[find(parent, i)].push_back(email);
vector<vector<string>> merged;
for (int i = 0; i < n; i++) {
if (!groups.count(i))
continue;
vector<string> account = {accounts[i][0]};
sort(groups[i].begin(), groups[i].end());
account.insert(account.end(), groups[i].begin(), groups[i].end());
merged.push_back(account);
}
return merged;
}
private:
int find(vector<int> &parent, int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}
};
More Advanced Graphs problems
- Network Delay Time (Medium)
- Evaluate Division (Medium)
- Course Schedule II (Medium)
- Alien Dictionary (Hard)
- Redundant Connection (Medium)
- Number of Connected Components (Union-Find) (Medium)
- Minimum Spanning Tree (Kruskal) (Medium)
- Minimum Spanning Tree (Prim) (Medium)
- Min Cost to Connect All Points (Medium)
- Cheapest Flights Within K Stops (Medium)
- Bellman-Ford (negative weights) (Medium)
- Find the City (Floyd-Warshall) (Medium)
- Critical Connections in a Network (Hard)
- Articulation Points (Cut Vertices) (Hard)
- Strongly Connected Components (Hard)
- Reconstruct Itinerary (Hard)
- Minimum Height Trees (Medium)