Graphs Union-find
467. Accounts Merge
You are given a list of accounts. Each account is a list of strings: accounts[i][0] is a name, and the
rest of the list are email addresses that belong to that account.
Two accounts belong to the same person if they share at least one email. This carries over: if account A shares an email with account B, and B shares one with account C, then A, B and C all belong to one person, even if A and C share nothing. Two different people can have the same name, so a shared name alone does not join two accounts.
Merge all the accounts of each person into one, and return the merged accounts. A merged account is the
person's name followed by all of their emails, each email once, sorted in ASCII order. In that order .
comes before the digits, the digits before @, @ before _, and _ before the letters. The accounts
themselves can come back in any order.
The examples write each account as one string: its name and then its emails, separated by spaces. Your
function receives each account as a list of strings, so "Ravi ravi@mail.com" arrives as
["Ravi","ravi@mail.com"].
Example 1
Input: accounts = ["Asha asha@mail.com asha.k@work.io",
"Ravi ravi@mail.com",
"Asha asha_k@home.net asha@mail.com",
"Asha asha99@mail.com"]
[["Asha","asha.k@work.io","asha@mail.com","asha_k@home.net"],
["Asha","asha99@mail.com"],
["Ravi","ravi@mail.com"]]Explanation: The first and third accounts share asha@mail.com, so they are one person with three emails. The last
Asha shares no email with them, so she is a different person with the same name.
Example 2
Input: accounts = ["Mei mei@a.org",
"Mei mei@b.org mei@c.org",
"Mei mei@c.org mei@a.org"]
[["Mei","mei@a.org","mei@b.org","mei@c.org"]]Explanation: The first two accounts share nothing. The third shares mei@a.org with the first and mei@c.org with
the second, so all three belong to one person.
Example 3
Input: accounts = ["Tom tom@x.io tom@x.io", "Ann ann@x.io"]
[["Ann","ann@x.io"],["Tom","tom@x.io"]]Explanation: Tom's account lists the same email twice. His merged account lists it once.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ accounts.length ≤ 1052 ≤ accounts[i].length: every account has a name and at least one email- The accounts hold at most 105 emails in all, counting repeats.
accounts[i][0]is 1 to 10 English letters.- Every email is 1 to 30 characters long, made of lowercase English letters, digits,
.,_and@. - Two accounts that share an email have the same name.
Clarifying questions
What you would ask an interviewer before writing any code.