MediumArrayHash TableStringDepth-First SearchBreadth-First SearchUnion FindSorting

Accounts Merge

LeetCode
1 approach, code in all languages

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 <= 1000
  • 2 <= accounts[i].length <= 10
  • 1 <= accounts[i][j].length <= 30
  • accounts[i][0] consists of English letters.
  • accounts[i][j] (for j > 0) is a valid email address.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now