medium +28 pts

Accounts Merge

Merge user accounts that share at least one email, preserving input order.

You are given a list of accounts where each account is a list of strings: the first element is the name, and the rest are emails associated with that account. Two accounts belong to the same person if they share at least one common email. Merge the accounts of the same person, and for each merged account, return it in the format: [name, sorted emails...]. When merging, keep the name from the earliest account in the input list that contributed to the merged group. The final output must preserve the order of first appearance: a merged account's position is determined by the position of the first account (in the original list) that belongs to it. If two merged groups have the same first-account index, order them by that index. Emails in each output account must be sorted lexicographically. You must implement the function `merge_accounts(accounts)` that takes a list of lists of strings and returns a list of lists of strings. Note: The input contains no duplicate emails within the same account. Both the input and the output are in-memory lists; no file or network I/O is needed.

Constraints

1 <= len(accounts) <= 1000 1 <= len(account[i]) <= 20 The total number of emails across all accounts is at most 5000. Emails are valid strings containing '@' and are unique within an account. Each account name is a non-empty string.

Example

>>> merge_accounts([["John", "johnsmith@mail.com", "john00@mail.com"], ["John", "johnnybravo@mail.com"], ["John", "johnsmith@mail.com", "john_newyork@mail.com"], ["Mary", "mary@mail.com"]])
[['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com'], ['John', 'johnnybravo@mail.com'], ['Mary', 'mary@mail.com']]
28 points ~30 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Think of each account as a node; connect accounts that share an email.
Use a dictionary to map each email to the first account index that contains it.
Union accounts when an email appears in two different indices.
After grouping, collect emails per root and sort them.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.