- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 55 lines of Java from the credited upstream file 721.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 9 loop blocks detected.
Complexity
Account for every find and union operation; with path compression and ranked merging, the amortized cost is nearly constant per operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class UnionFind {2 public UnionFind(List<List<String>> accounts) {3 for (List<String> account : accounts)4 for (int i = 1; i < account.size(); ++i) {5 final String email = account.get(i);6 id.putIfAbsent(email, email);7 }8 }9 10 public void union(final String u, final String v) {11 id.put(find(u), find(v));12 }13 14 public String find(final String u) {15 if (u != id.get(u))16 id.put(u, find(id.get(u)));17 return id.get(u);18 }19 20 private Map<String, String> id = new HashMap<>();21}22 23class Solution {24 public List<List<String>> accountsMerge(List<List<String>> accounts) {25 List<List<String>> ans = new ArrayList<>();26 Map<String, String> emailToName = new HashMap<>();27 Map<String, TreeSet<String>> idEmailToEmails = new HashMap<>();28 UnionFind uf = new UnionFind(accounts);29 30 for (final List<String> account : accounts)31 for (int i = 1; i < account.size(); ++i)32 emailToName.putIfAbsent(account.get(i), account.get(0));33 34 for (final List<String> account : accounts)35 for (int i = 2; i < account.size(); ++i)36 uf.union(account.get(i), account.get(i - 1));37 38 for (final List<String> account : accounts)39 for (int i = 1; i < account.size(); ++i) {40 final String id = uf.find(account.get(i));41 idEmailToEmails.putIfAbsent(id, new TreeSet<>());42 idEmailToEmails.get(id).add(account.get(i));43 }44 45 for (final String idEmail : idEmailToEmails.keySet()) {46 List<String> emails = new ArrayList<>(idEmailToEmails.get(idEmail));47 final String name = emailToName.get(idEmail);48 emails.add(0, name);49 ans.add(emails);50 }51 52 return ans;53 }54}55