Skip to content

Commit d64419b

Browse files
author
openset
committed
Add: Accounts Merge
1 parent 87bc270 commit d64419b

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,45 @@
11
package accounts_merge
2+
3+
import "sort"
4+
5+
func accountsMerge(accounts [][]string) [][]string {
6+
n := len(accounts)
7+
owner := make(map[string]string, n)
8+
parent := make(map[string]string, n*2)
9+
for _, a := range accounts {
10+
for i := 1; i < len(a); i++ {
11+
parent[a[i]] = a[i]
12+
owner[a[i]] = a[0]
13+
}
14+
}
15+
for _, a := range accounts {
16+
r := root(a[1], parent)
17+
for i := 2; i < len(a); i++ {
18+
p := root(a[i], parent)
19+
parent[p] = r
20+
}
21+
}
22+
union := make(map[string][]string, n)
23+
for email, p := range parent {
24+
r := root(p, parent)
25+
union[r] = append(union[r], email)
26+
}
27+
res := make([][]string, 0, len(union))
28+
for p, emails := range union {
29+
t := make([]string, len(emails)+1)
30+
t[0] = owner[p]
31+
if len(emails) > 1 {
32+
sort.Strings(emails)
33+
}
34+
copy(t[1:], emails)
35+
res = append(res, t)
36+
}
37+
return res
38+
}
39+
40+
func root(e string, parent map[string]string) string {
41+
if parent[e] == e {
42+
return e
43+
}
44+
return root(parent[e], parent)
45+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,34 @@
11
package accounts_merge
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
)
7+
8+
type caseType struct {
9+
input [][]string
10+
expected [][]string
11+
}
12+
13+
func TestAccountsMerge(t *testing.T) {
14+
tests := [...]caseType{
15+
{
16+
input: [][]string{
17+
{"John", "johnsmith@mail.com", "john00@mail.com"},
18+
{"John", "johnnybravo@mail.com"},
19+
{"John", "johnsmith@mail.com", "john_newyork@mail.com"},
20+
{"Mary", "mary@mail.com"},
21+
},
22+
expected: [][]string{
23+
{"John", "john00@mail.com", "john_newyork@mail.com", "johnsmith@mail.com"},
24+
{"John", "johnnybravo@mail.com"}, {"Mary", "mary@mail.com"},
25+
},
26+
},
27+
}
28+
for _, tc := range tests {
29+
output := accountsMerge(tc.input)
30+
if !reflect.DeepEqual(output, tc.expected) {
31+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
32+
}
33+
}
34+
}

0 commit comments

Comments
 (0)