Accounts Merge
1 approach, code in every language
Problem description
You are given a list of accounts, where accounts[i] is [name, email1, email2, ...]. The first element is a person's name and the rest are the emails belonging to that account.
Two accounts definitely belong to the same person if they share at least one common email, even if the names look identical. Note that a single person can have any number of accounts, but all of their accounts use the same name; conversely, different people may share the same name.
Merge the accounts so that each person is represented once. Return the merged accounts in the format [name, sortedEmail1, sortedEmail2, ...], where the emails are sorted in lexicographic order. The accounts themselves may be returned in any order.
Example 1
Input: accounts = [["John","johnsmith@mail.com","john_newyork@mail.com"],["John","johnsmith@mail.com","john00@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]
Output: [["John","john00@mail.com","john_newyork@mail.com","johnsmith@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]
The first two John accounts share "johnsmith@mail.com", so they merge into one. The third John (johnnybravo) shares no email and stays separate, and Mary is untouched.
Example 2
Input: accounts = [["Alex","alex1@m.com","alex2@m.com"],["Alex","alex2@m.com","alex3@m.com"],["Bob","bob1@m.com"]]
Output: [["Alex","alex1@m.com","alex2@m.com","alex3@m.com"],["Bob","bob1@m.com"]]
The two Alex accounts share "alex2@m.com" and merge into one sorted list; Bob remains on his own.
Constraints
1 <= accounts.length <= 10002 <= accounts[i].length <= 101 <= accounts[i][j].length <= 30accounts[i][0] consists of English letters.accounts[i][j] (for j > 0) is a valid email address.
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Merge Crew Badge Records is our own problem on the technique behind Accounts Merge: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free