Given a list accounts
, each element accounts[i]
is a list of strings, where the first element accounts[i][0]
is a name, and the rest of the elements are emails representing emails of the account.
Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some email that is common to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.
After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order.
Example 1:
Input: accounts = [["John", "johnsmith@mail.com", "john00@mail.com"], ["John", "johnnybravo@mail.com"], ["John", "johnsmith@mail.com", "john_newyork@mail.com"], ["Mary", "mary@mail.com"]] Output: [["John", 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com'], ["John", "johnnybravo@mail.com"], ["Mary", "mary@mail.com"]] Explanation: The first and third John's are the same person as they have the common email "johnsmith@mail.com". The second John and Mary are different people as none of their email addresses are used by other accounts. We could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'], ['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.
Note:
accounts
will be in the range [1, 1000]
.accounts[i]
will be in the range [1, 10]
.accounts[i][j]
will be in the range [1, 30]
.Intuition
\nDraw an edge between two emails if they occur in the same account. The problem comes down to finding connected components of this graph.
\nAlgorithm
\nFor each account, draw the edge from the first email to all other emails. Additionally, we\'ll remember a map from emails to names on the side. After finding each connected component using a depth-first search, we\'ll add that to our answer.
\nPython
\nclass Solution(object):\n def accountsMerge(self, accounts):\n em_to_name = {}\n graph = collections.defaultdict(set)\n for acc in accounts:\n name = acc[0]\n for email in acc[1:]:\n graph[acc[1]].add(email)\n graph[email].add(acc[1])\n em_to_name[email] = name\n\n seen = set()\n ans = []\n for email in graph:\n if email not in seen:\n seen.add(email)\n stack = [email]\n component = []\n while stack:\n node = stack.pop()\n component.append(node)\n for nei in graph[node]:\n if nei not in seen:\n seen.add(nei)\n stack.append(nei)\n ans.append([em_to_name[email]] + sorted(component))\n return ans\n
Java
\nclass Solution {\n public List<List<String>> accountsMerge(List<List<String>> accounts) {\n Map<String, String> emailToName = new HashMap();\n Map<String, ArrayList<String>> graph = new HashMap();\n for (List<String> account: accounts) {\n String name = "";\n for (String email: account) {\n if (name == "") {\n name = email;\n continue;\n }\n graph.computeIfAbsent(email, x-> new ArrayList<String>()).add(account.get(1));\n graph.computeIfAbsent(account.get(1), x-> new ArrayList<String>()).add(email);\n emailToName.put(email, name);\n }\n }\n\n Set<String> seen = new HashSet();\n List<List<String>> ans = new ArrayList();\n for (String email: graph.keySet()) {\n if (!seen.contains(email)) {\n seen.add(email);\n Stack<String> stack = new Stack();\n stack.push(email);\n List<String> component = new ArrayList();\n while (!stack.empty()) {\n String node = stack.pop();\n component.add(node);\n for (String nei: graph.get(node)) {\n if (!seen.contains(nei)) {\n seen.add(nei);\n stack.push(nei);\n }\n }\n }\n Collections.sort(component);\n component.add(0, emailToName.get(email));\n ans.add(component);\n }\n }\n return ans;\n }\n}\n
Complexity Analysis
\nTime Complexity: , where is the length of accounts[i]
. Without the log factor, this is the complexity to build the graph and search for each component. The log factor is for sorting each component at the end.
Space Complexity: , the space used by our graph and our search.
\nIntuition
\nAs in Approach #1, our problem comes down to finding the connected components of a graph. This is a natural fit for a Disjoint Set Union (DSU) structure.
\nAlgorithm
\nAs in Approach #1, draw edges between emails if they occur in the same account. For easier interoperability between our DSU template, we will map each email to some integer index by using emailToID
. Then, dsu.find(email)
will tell us a unique id representing what component that email is in.
For more information on DSU, please look at Approach #2 in the article here. For brevity, the solutions showcased below do not use union-by-rank.
\nPython
\nclass DSU:\n def __init__(self):\n self.p = range(10001)\n def find(self, x):\n if self.p[x] != x:\n self.p[x] = self.find(self.p[x])\n return self.p[x]\n def union(self, x, y):\n self.p[self.find(x)] = self.find(y)\n\nclass Solution(object):\n def accountsMerge(self, accounts):\n dsu = DSU()\n em_to_name = {}\n em_to_id = {}\n i = 0\n for acc in accounts:\n name = acc[0]\n for email in acc[1:]:\n em_to_name[email] = name\n if email not in em_to_id:\n em_to_id[email] = i\n i += 1\n dsu.union(em_to_id[acc[1]], em_to_id[email])\n\n ans = collections.defaultdict(list)\n for email in em_to_name:\n ans[dsu.find(em_to_id[email])].append(email)\n\n return [[em_to_name[v[0]]] + sorted(v) for v in ans.values()]\n
Java
\nclass Solution {\n public List<List<String>> accountsMerge(List<List<String>> accounts) {\n DSU dsu = new DSU();\n Map<String, String> emailToName = new HashMap();\n Map<String, Integer> emailToID = new HashMap();\n int id = 0;\n for (List<String> account: accounts) {\n String name = "";\n for (String email: account) {\n if (name == "") {\n name = email;\n continue;\n }\n emailToName.put(email, name);\n if (!emailToID.containsKey(email)) {\n emailToID.put(email, id++);\n }\n dsu.union(emailToID.get(account.get(1)), emailToID.get(email));\n }\n }\n\n Map<Integer, List<String>> ans = new HashMap();\n for (String email: emailToName.keySet()) {\n int index = dsu.find(emailToID.get(email));\n ans.computeIfAbsent(index, x-> new ArrayList()).add(email);\n }\n for (List<String> component: ans.values()) {\n Collections.sort(component);\n component.add(0, emailToName.get(component.get(0)));\n }\n return new ArrayList(ans.values());\n }\n}\nclass DSU {\n int[] parent;\n public DSU() {\n parent = new int[10001];\n for (int i = 0; i <= 10000; ++i)\n parent[i] = i;\n }\n public int find(int x) {\n if (parent[x] != x) parent[x] = find(parent[x]);\n return parent[x];\n }\n public void union(int x, int y) {\n parent[find(x)] = find(y);\n }\n}\n
Complexity Analysis
\nTime Complexity: , where , and is the length of accounts[i]
. If we used union-by-rank, this complexity improves to , where is the Inverse-Ackermann function.
Space Complexity: , the space used by our DSU structure.
\nAnalysis written by: @awice.
\n