Given a list of accounts where 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 common email 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","john_newyork@mail.com"],["John","johnsmith@mail.com","john00@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]
Output: [["John","john00@mail.com","john_newyork@mail.com","johnsmith@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]
Explanation:
The first and second John's are the same person as they have the common email "johnsmith@mail.com".
The third 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.
Accounts of the same person share emails and must be merged, then sorted. About \(1000\) accounts makes pairwise set comparison awkward, and names must stay attached.
The connectivity is among accounts: two indices join if they share an email. Union-find on account ids, plus a map from email to the first account that used it, finds those edges.
Group emails by root, take the root account's name, and sort. Path compression keeps the cost near linearithmic.
Based on the problem description, we can use a union-find data structure to merge accounts with the same email address. The specific steps are as follows:
First, we iterate through all the accounts. For the \(i\)th account, we iterate through all its email addresses. If an email address appears in the hash table \(\textit{d}\), we use the union-find to merge the account's index \(i\) with the previously appeared account's index; otherwise, we map this email address to the account's index \(i\).
Next, we iterate through all the accounts again. For the \(i\)th account, we use the union-find to find its root node, and then add all the email addresses of that account to the hash table \(\textit{g}\), where the key is the root node, and the value is the account's email addresses.
The time complexity is \(O(n \times \log n)\), and the space complexity is \(O(n)\). Here, \(n\) is the number of accounts.