Given a list of accounts where each element contains a name followed by email addresses, merge all accounts that share common emails. Each account belongs to one person, identified by their name and email addresses. Two accounts should be merged if they share at least one email address.
Merging is transitive: if account A shares an email with account B, and B shares an email with account C, all three belong to the same person. Two accounts with the same name that are not linked by any chain of shared emails may belong to different people and stay separate.
Return the merged accounts. Each merged account is the name followed by all of that person's emails.
Function Signature
def merge_accounts(accounts: list[list[str]]) -> list[list[str]]:
Rules
-
accounts[i][0]
is the name and
accounts[i][1:]
are that account's emails.
-
Accounts that share an email always have the same name.
-
In each merged account, list every email once, sorted in ascending order by character code (Python's default string order, so
.
< digits <
@
<
_
< lowercase letters).
-
Sort the merged accounts by name, then by their first (smallest) email. Two merged accounts never share an email, so this order is unique.
Constraints
-
1 <= len(accounts) <= 1000
-
2 <= len(accounts[i]) <= 10
-
1 <= len(accounts[i][j]) <= 30
-
accounts[i][0]
is a name.
-
accounts[i][j]
for
j >= 1
is a valid email address in lowercase.
Examples
Input: accounts = [["John","johnsmith@mail.com","john_newyork@mail.com"],
["John","johnsmith@mail.com","john_chicago@mail.com"],
["Mary","mary@mail.com"]]
Output: [["John","john_chicago@mail.com","john_newyork@mail.com","johnsmith@mail.com"],
["Mary","mary@mail.com"]]
The two John accounts share johnsmith@mail.com, so they merge into one account with three emails. _ sorts before s, which puts john_chicago and john_newyork ahead of johnsmith.
Input: accounts = [["Gabe","gabe@example.com","gabe.work@example.com"],
["Alex","alex@example.com"],
["Gabe","gabe.work@example.com","gabe.personal@example.com"]]
Output: [["Alex","alex@example.com"],
["Gabe","gabe.personal@example.com","gabe.work@example.com","gabe@example.com"]]
The first and third accounts share gabe.work@example.com. Alex sorts before Gabe, and . sorts before @, so gabe@example.com comes last.
Input: accounts = [["Ann","ann1@mail.com","ann2@mail.com"],
["Bob","bob@mail.com"],
["Ann","ann3@mail.com","ann4@mail.com"],
["Ann","ann2@mail.com","ann3@mail.com"],
["Ann","ann9@mail.com"]]
Output: [["Ann","ann1@mail.com","ann2@mail.com","ann3@mail.com","ann4@mail.com"],
["Ann","ann9@mail.com"],
["Bob","bob@mail.com"]]
The first and third Ann accounts share no email, but the fourth account links them through ann2@mail.com and ann3@mail.com. The last Ann account shares nothing with the others, so it stays separate, and the two Ann rows are ordered by their first emails.