6
public UnionFind(int num) {10
for (int i = 0; i < num; i++) {16
public void union(int a, int b) {24
if (weight[rootA] > weight[rootB]) {25
parent[rootB] = rootA;26
weight[rootA] += weight[rootB];28
parent[rootA] = rootB;29
weight[rootB] += weight[rootA];33
public int root(int a) {38
parent[a] = root(parent[a]);43
public List<List<String>> accountsMerge(List<List<String>> accounts) {44
int size = accounts.size();46
UnionFind uf = new UnionFind(size);48
// prepare a hash with unique email address as key and index in accouts as value49
HashMap<String, Integer> emailToId = new HashMap<>();50
for (int i = 0; i < size; i++) {51
List<String> details = accounts.get(i);52
for (int j = 1; j < details.size(); j++) {53
String email = details.get(j);55
// if we have already seen this email before, merge the account "i" with previous account56
// else add it to hash57
if (emailToId.containsKey(email)) {58
uf.union(i, emailToId.get(email));60
emailToId.put(email, i);65
// prepare a hash with index in accounts as key and list of unique email address for that67
HashMap<Integer, List<String>> idToEmails = new HashMap<>();68
for (String key : emailToId.keySet()) {69
int root = uf.root(emailToId.get(key));71
if (!idToEmails.containsKey(root)) {72
idToEmails.put(root, new ArrayList<String>());75
idToEmails.get(root).add(key);78
// collect the emails from idToEmails, sort it and add account name at index 0 to get the final79
// list to add to final return List80
List<List<String>> mergedDetails = new ArrayList<>();81
for (Integer id : idToEmails.keySet()) {82
List<String> emails = idToEmails.get(id);83
Collections.sort(emails);84
emails.add(0, accounts.get(id).get(0));86
mergedDetails.add(emails);