@@ -66,13 +66,13 @@ public List<List<String>> accountsMerge(List<List<String>> accounts) {
66
66
public static class Solution2 {
67
67
/**
68
68
* credit: https://leetcode.com/articles/accounts-merge/#approach-2-union-find-accepted
69
- * DSU stands for Disjoint Set Union: https://en.wikipedia.org/wiki/Disjoint-set_data_structure
69
+ * DSU stands for Disjoint Set Union: https://en.wikipedia.org/wiki/Disjoint-set_data_structure, a.k.a Union Find data structure.
70
70
* <p>
71
- * Time complexity: O(AlogA )
72
- * Space complexity: O(A )
71
+ * Time complexity: O(nlogn )
72
+ * Space complexity: O(n )
73
73
*/
74
74
public List <List <String >> accountsMerge (List <List <String >> accounts ) {
75
- DSU dsu = new DSU ();
75
+ UnionFind uf = new UnionFind ();
76
76
Map <String , String > emailToName = new HashMap <>();
77
77
Map <String , Integer > emailToId = new HashMap <>();
78
78
int id = 0 ;
@@ -87,28 +87,31 @@ public List<List<String>> accountsMerge(List<List<String>> accounts) {
87
87
if (!emailToId .containsKey (email )) {
88
88
emailToId .put (email , id ++);
89
89
}
90
- dsu .union (emailToId .get (account .get (1 )), emailToId .get (email ));
90
+ uf .union (emailToId .get (account .get (1 )), emailToId .get (email ));
91
91
}
92
92
}
93
93
94
- Map <Integer , List <String >> ans = new HashMap <>();
94
+ Map <Integer , List <String >> map = new HashMap <>();
95
95
for (String email : emailToName .keySet ()) {
96
- int index = dsu .find (emailToId .get (email ));
97
- ans .computeIfAbsent (index , x -> new ArrayList ()).add (email );
96
+ //find the index of this email first: use this email's ID to find its parent in the Union Find
97
+ int index = uf .find (emailToId .get (email ));
98
+ map .computeIfAbsent (index , x -> new ArrayList ()).add (email );
98
99
}
99
- for (List <String > component : ans .values ()) {
100
+ for (List <String > component : map .values ()) {
100
101
Collections .sort (component );
102
+ //this is to add name to the head of the list
101
103
component .add (0 , emailToName .get (component .get (0 )));
102
104
}
103
- return new ArrayList <>(ans .values ());
105
+ return new ArrayList <>(map .values ());
104
106
}
105
107
106
- class DSU {
108
+ class UnionFind {
107
109
int [] parent ;
110
+ int size = 10001 ;
108
111
109
- public DSU () {
110
- parent = new int [10001 ];
111
- for (int i = 0 ; i <= 10000 ; i ++) {
112
+ public UnionFind () {
113
+ parent = new int [size ];
114
+ for (int i = 0 ; i < size ; i ++) {
112
115
parent [i ] = i ;
113
116
}
114
117
}
@@ -121,7 +124,7 @@ public int find(int x) {
121
124
}
122
125
123
126
public void union (int x , int y ) {
124
- parent [find (x )] = find (y );
127
+ parent [find (x )] = find (y );//can be written as parent[find(y)] = find(x); they are equivalent
125
128
}
126
129
}
127
130
}
0 commit comments