| 1 | class Solution { |
| 2 | public List<List<String>> accountsMerge(List<List<String>> accounts) { |
| 3 | int n = accounts.size(); |
| 4 | DSU dsu = new DSU(n); |
| 5 | |
| 6 | Map<String, Integer> map = new HashMap<>(); // email -> index of acc |
| 7 | |
| 8 | for(int i = 0; i < n; i++){ |
| 9 | for(int j = 1; j < accounts.get(i).size(); j++){ |
| 10 | String email = accounts.get(i).get(j); |
| 11 | String name = accounts.get(i).get(0); |
| 12 | |
| 13 | if(!map.containsKey(email)) |
| 14 | map.put(email, i); |
| 15 | else |
| 16 | dsu.union(i, map.get(email)); |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | Map<Integer, List<String>> merged = new HashMap<>(); // index of acc -> list of emails |
| 21 | for(String email : map.keySet()){ |
| 22 | int group = map.get(email); |
| 23 | int lead = dsu.find(group); |
| 24 | |
| 25 | if(!merged.containsKey(lead)) |
| 26 | merged.put(lead, new ArrayList<String>()); |
| 27 | |
| 28 | merged.get(lead).add(email); |
| 29 | } |
| 30 | |
| 31 | List<List<String>> res = new ArrayList<>(); |
| 32 | for(int ac : merged.keySet()){ |
| 33 | List<String> grp = merged.get(ac); |
| 34 | Collections.sort(grp); |
| 35 | grp.add(0, accounts.get(ac).get(0)); |
| 36 | res.add(grp); |
| 37 | } |
| 38 | return res; |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | class DSU { |