Merge User Accounts By Email
Identity resolution merges duplicate accounts: two account records belong to the same person if they share any email. Merge all transitively-linked accounts and emit each person's full, de-duplicated, sorted email list.
Problem
Each account is a list [name, email1, email2, …]. Two accounts are the same person if they share at least one email (names may repeat across different people). Merge accounts and return, for each merged person, [name, sortedUniqueEmails…]. Order of output accounts is arbitrary.
Input
A list of accounts, each a list whose first item is a name and the rest emails.
Output
A list of merged accounts, each name followed by its emails in sorted order.
Constraints
- 1 ≤ accounts.length ≤ 1000
- Emails within one account are unique
- Shared emails link accounts transitively
Examples
Example 1
Input
accounts = [["John","a@x.com","b@x.com"],["John","b@x.com","c@x.com"],["Mary","m@x.com"]]
Output
[["John","a@x.com","b@x.com","c@x.com"],["Mary","m@x.com"]]
The two Johns share b@x.com and merge; Mary stays separate.
Example 2
Input
accounts = [["A","x@x.com"],["B","x@x.com"]]
Output
[["A","x@x.com"]] (name from the root account)
Same email links them; one merged record results.