-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaccountsMerge.ts
69 lines (54 loc) · 1.65 KB
/
accountsMerge.ts
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { compareFn } from 'utils/compareFn/alphabeticallyCompareFn'
// <Recursion, DFS, HashTable>
// Time: O(nlogn)
// Space: O(n)
function dfs(
accounts: string[][],
emailSet: Set<string>,
emailToIndexes: Map<string, number[]>,
visited: boolean[],
index: number,
) {
visited[index] = true
for (let i = 1; i < accounts[index].length; ++i) {
const email = accounts[index][i]
if (emailSet.has(email)) {
continue
}
emailSet.add(email)
for (const j of emailToIndexes.get(email)!) {
if (!visited[j]) {
dfs(accounts, emailSet, emailToIndexes, visited, j)
}
}
}
}
function accountsMerge(accounts: string[][]): string[][] {
// edge cases
if (!accounts.length) {
return []
}
const n = accounts.length
const emailToIndexes = new Map<string, number[]>() // Map<email, index[]>
for (let i = 0; i < n; ++i) {
for (let j = 1; j < accounts[i].length; ++j) {
const email = accounts[i][j]
if (!emailToIndexes.has(email)) {
emailToIndexes.set(email, [])
}
emailToIndexes.get(email)!.push(i)
}
}
const visited: boolean[] = new Array(n)
const emailSet = new Set<string>() // Set<email>
const mergedAccounts: string[][] = []
for (let i = 0; i < n; ++i) {
if (!visited[i]) {
emailSet.clear()
dfs(accounts, emailSet, emailToIndexes, visited, i)
mergedAccounts.push([accounts[i][0], ...Array.from(emailSet).sort(compareFn)])
}
}
return mergedAccounts
}
export { accountsMerge }