1049. Accounts Merge

MediumGraphsDSUGraph

Given a list of accounts where each account is [name, email1, email2, ...], merge accounts that share any email (the same person may have multiple accounts). Two accounts belong to the same person if they share at least one email; names may repeat across different people. Return the merged accounts, each as [name, ...sorted emails], with the overall list sorted. The input is JSON {accounts}.

Input: JSON {accounts}.

Output: Nested array — merged accounts, sorted.

Examples

Example 1
Input: {"accounts":[["John","[email protected]","[email protected]"],["John","[email protected]","[email protected]"],["Mary","[email protected]"]]}
Output: [["John","[email protected]","[email protected]","[email protected]"],["Mary","[email protected]"]]
Explanation: The two Johns share [email protected].
Example 2
Input: {"accounts":[["A","[email protected]"]]}
Output: [["A","[email protected]"]]
Explanation: Single account.
Example 3
Input: {"accounts":[["A","[email protected]"],["B","[email protected]"]]}
Output: [["A","[email protected]"],["B","[email protected]"]]
Explanation: No shared email.

Constraints

Asked by

MetaAmazonBloombergMicrosoftGoogle
Solve this problem in the editor →