DIY: Accounts Merge

Solve the interview question "Accounts Merge" in this lesson.

Problem statement

In this challenge, you are given a 2D array called accounts. Each element in accounts[i] is an array of strings in which accounts[i][0] is a name and the remaining elements are email, representing the emails associated with that account.

Your task is to merge these accounts such that two accounts belonging to the same person become one. To check if two accounts belong to the same person, you have to determine whether both accounts have at least one email in common.

Note that even if two accounts have the same name, they may belong to different people as people can share the same name. However, all accounts that belong to one person will have the same name. There can be more than two accounts made by one person.

Input

The input will be a 2D array of strings, where the nested arrays represent a single account. The first string in an account will be the name while the rest of the strings will be type email. The following is an example input:

accounts = [["Micheal", "michealjordan@mail.com", "mikey@mail.com"], ["Lily","Lily4@mail.com","Lily6@mail.com","Lily7@mail.com"], ["Lily", "lilysmith@mail.com", "lily@mail.com"], ["Micheal", "mikey@mail.com", "micheal2@mail.com"]]

Output

The output will be a list of merged accounts. While merging, we need to put all distinct email addresses for the same person into a single consolidated record. The output should have the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The output for the above-mentioned inputs will be:

[["Micheal", "michealjordan@mail.com", "mikey@mail.com", "micheal2@mail.com"], ["Lily","Lily4@mail.com","Lily6@mail.com","Lily7@mail.com"], ["Lily", "lilysmith@mail.com", "lily@mail.com"]]

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.