File tree 1 file changed +52
-0
lines changed
1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ from collections import defaultdict
2
+
3
+ class Solution (object ):
4
+ def accountsMerge (self , accounts ):
5
+ graph = defaultdict (list )
6
+ merged = set ()
7
+ ans = []
8
+
9
+ #[0]
10
+ for data in accounts :
11
+ emails = data [1 :]
12
+ for i , email in enumerate (emails ):
13
+ graph [email ].extend (emails [:i ])
14
+ graph [email ].extend (emails [i + 1 :])
15
+
16
+ for data in accounts :
17
+ name = data [0 ]
18
+ visited = set ()
19
+ stack = [data [1 ]]
20
+
21
+ if data [1 ] in merged : continue #[1]
22
+
23
+ while stack :
24
+ e = stack .pop ()
25
+ if e in visited : continue
26
+ visited .add (e )
27
+ stack .extend (graph [e ])
28
+
29
+ merged .update (visited )
30
+ ans .append ([name ]+ sorted (list (visited )))
31
+
32
+ return ans
33
+
34
+ """
35
+ Treat each email as a node.
36
+ Build an adjacency graph. [0]
37
+
38
+ For every account's data
39
+ First, lets check if the first email is already merged. [1]
40
+ If the first email is already merged to other groups, then other emails will be in another group as well.
41
+ So don't need to check.
42
+
43
+ Second, do a DFS starting from the first email. Put all the connected nodes into visited.
44
+ And append it to the ans with name.
45
+
46
+ Let N be the total number of emails. M be the total number of final groups.
47
+ Build the graph takes O(N).
48
+ For each final groups, we make a DFS to all nodes, taking O(MN).
49
+ Sort the group takes O((N/M)*Log(N/M)) -> O((N/M)*(logN-LogM))
50
+ Time: O(MN)
51
+ Space: O(N)
52
+ """
You can’t perform that action at this time.
0 commit comments