Problem description:

Given a list accounts, each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account.

Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some email that is common to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.

After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order.

Example 1:

1
2
3
4
5
6
7
8
Input: 
accounts = [["John", "johnsmith@mail.com", "john00@mail.com"], ["John", "johnnybravo@mail.com"], ["John", "johnsmith@mail.com", "john_newyork@mail.com"], ["Mary", "mary@mail.com"]]
Output: [["John", 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com'], ["John", "johnnybravo@mail.com"], ["Mary", "mary@mail.com"]]
Explanation:
The first and third John's are the same person as they have the common email "johnsmith@mail.com".
The second John and Mary are different people as none of their email addresses are used by other accounts.
We could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'],
['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.

Note:
The length of accounts will be in the range [1, 1000].
The length of accounts[i] will be in the range [1, 10].
The length of accounts[i][j] will be in the range [1, 30].

Solution:

Union find: make every node it’s root. traverse all connection and make it in a union.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution:
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
root = defaultdict() # union find nodes, default each email would be its root
owner = defaultdict() # this email belongs to who
for name, *emails in accounts:
for email in emails:
root[email] = email
owner[email] = name

def find(s):
if root[s] == s:
return s
else:
return find(root[s])
for account in accounts:
p = find(account[1]) # first email of the account
for email in account[2:]:
root[find(email)] = p # make first email to be every rest email's root
# merge accounts together
merge = defaultdict(set)

for account in accounts:
for email in account[1:]:
merge[find(email)].add(email)

res = []
for k in merge.keys():
res.append([owner[k]]+ sorted(list(merge[k])))
return res
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
public:
vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {
vector<vector<string>> res;
unordered_map<string, string> root; //"john00@mail.com", "johnsmith@mail.com",
unordered_map<string, string> owner; //email, Name. ex: "johnsmith@mail.com", "John"
unordered_map<string, set<string>> m;

for(auto account: accounts){
for(int i= 1; i< account.size(); i++){
root[account[i]]= account[i]; //let every email in different group "johnsmith@mail.com", "johnsmith@mail.com".
owner[account[i]]= account[0]; //every account[i] owners is the first one
}
}

for(auto account: accounts){
string p= find(account[1], root);
for(int i= 2; i< account.size(); i++){
root[find(account[i], root)]= p;
}
}

for(auto account: accounts){
for(int i= 1; i< account.size(); i++){
m[find(account[i], root)].insert(account[i]); //put into same set
}
}
for (auto a : m) {
vector<string> v(a.second.begin(), a.second.end());
v.insert(v.begin(), owner[a.first]);
res.push_back(v);
}
return res;

}

string find(string s, unordered_map<string, string>& root){
// to check if s is in the same root group
return root[s]== s? s: find(root[s], root);
}
};

Solution BFS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
public:
vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {
//use BFS to solve

vector<vector<string>> res;
int n= accounts.size();
vector<bool> visited(n, false);
unordered_map<string, vector<int>> m;

for(int i= 0; i< n; i++){
for(int j= 1; j< accounts[i].size(); j++){
m[accounts[i][j]].push_back(i); // store where every email belong to user i
}
}

for(int i= 0; i< n; i++){
if(visited[i])
continue; //already visited
queue<int> q{{i}};
set<string> s;
while(!q.empty()){
auto t= q.front(); q.pop();
visited[t]= true;
vector<string> emails(accounts[t].begin()+1, accounts[t].end());
for(auto email: emails){
s.insert(email);
for(auto user: m[email]){
if(visited[user])
continue;
q.push(user);
visited[user]= true;
}
}
}
vector<string> out(s.begin(), s.end());
out.insert(out.begin(), accounts[i][0]);
res.push_back(out);
}
return res;

}
};

Python DFS

We give each account an ID, based on the index of it within the list of accounts.

1
2
3
4
5
6
[
["John", "johnsmith@mail.com", "john00@mail.com"], # Account 0
["John", "johnnybravo@mail.com"], # Account 1
["John", "johnsmith@mail.com", "john_newyork@mail.com"], # Account 2
["Mary", "mary@mail.com"] # Account 3
]

Next, build an emails_accounts_map that maps an email to a list of accounts, which can be used to track which email is linked to which account. This is essentially our graph.

1
2
3
4
5
6
7
8
# emails_accounts_map of email to account ID
{
"johnsmith@mail.com": [0, 2],
"john00@mail.com": [0],
"johnnybravo@mail.com": [1],
"john_newyork@mail.com": [2],
"mary@mail.com": [3]
}

Next we do a DFS on each account in accounts list and look up emails_accounts_map to tell us which accounts are linked to that particular account via common emails. This will make sure we visit each account only once. This is a recursive process and we should collect all the emails that we encounter along the way.

Lastly, sort the collected emails and add it to final results, res along with the name.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution:
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
visited_accounts = [False] * len(accounts)
emails_accounts_map = defaultdict(list)
res = []
# Build up the graph.
for i, account in enumerate(accounts):
for j in range(1, len(account)):
email = account[j]
emails_accounts_map[email].append(i)
# DFS code for traversing accounts.
def dfs(i, emails):
if visited_accounts[i]:
return
visited_accounts[i] = True
for j in range(1, len(accounts[i])):
email = accounts[i][j]
emails.add(email)
for neighbor in emails_accounts_map[email]:
dfs(neighbor, emails)
# Perform DFS for accounts and add to results.
for i, account in enumerate(accounts):
if visited_accounts[i]:
continue
name, emails = account[0], set()
dfs(i, emails)
res.append([name] + sorted(emails))
return res

time complexity: $O()$
space complexity: $O()$
reference: