Skip to content

Commit a1ed359

Browse files
committed
Add solution #721
1 parent 71848dc commit a1ed359

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -546,6 +546,7 @@
546546
718|[Maximum Length of Repeated Subarray](./0718-maximum-length-of-repeated-subarray.js)|Medium|
547547
719|[Find K-th Smallest Pair Distance](./0719-find-k-th-smallest-pair-distance.js)|Hard|
548548
720|[Longest Word in Dictionary](./0720-longest-word-in-dictionary.js)|Medium|
549+
721|[Accounts Merge](./0721-accounts-merge.js)|Medium|
549550
722|[Remove Comments](./0722-remove-comments.js)|Medium|
550551
724|[Find Pivot Index](./0724-find-pivot-index.js)|Easy|
551552
733|[Flood Fill](./0733-flood-fill.js)|Easy|

solutions/0721-accounts-merge.js

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* 721. Accounts Merge
3+
* https://leetcode.com/problems/accounts-merge/
4+
* Difficulty: Medium
5+
*
6+
* Given a list of accounts where each element accounts[i] is a list of strings, where the first
7+
* element accounts[i][0] is a name, and the rest of the elements are emails representing emails
8+
* of the account.
9+
*
10+
* Now, we would like to merge these accounts. Two accounts definitely belong to the same person
11+
* if there is some common email to both accounts. Note that even if two accounts have the same
12+
* name, they may belong to different people as people could have the same name. A person can
13+
* have any number of accounts initially, but all of their accounts definitely have the same name.
14+
*
15+
* After merging the accounts, return the accounts in the following format: the first element of
16+
* each account is the name, and the rest of the elements are emails in sorted order. The accounts
17+
* themselves can be returned in any order.
18+
*/
19+
20+
/**
21+
* @param {string[][]} accounts
22+
* @return {string[][]}
23+
*/
24+
var accountsMerge = function(accounts) {
25+
const parent = new Map();
26+
const names = new Map();
27+
const groups = new Map();
28+
29+
const find = node => {
30+
if (!parent.has(node)) parent.set(node, node);
31+
return parent.get(node) === node ? node : parent.set(node, find(parent.get(node))).get(node);
32+
};
33+
34+
for (const [name, ...emails] of accounts) {
35+
for (const email of emails) {
36+
names.set(email, name);
37+
find(email);
38+
parent.set(find(email), find(emails[0]));
39+
}
40+
}
41+
42+
for (const email of parent.keys()) {
43+
const root = find(email);
44+
if (!groups.has(root)) groups.set(root, new Set());
45+
groups.get(root).add(email);
46+
}
47+
48+
return Array.from(groups, ([root, emails]) => [names.get(root), ...[...emails].sort()]);
49+
};

0 commit comments

Comments
 (0)