Accounts Merge

Medium#721

You get a list of accounts: each is a name followed by emails. Two accounts belong to one person when they share an email, also through other accounts; one name does not make one person. Merge the accounts of each person and return each person as the name followed by all their emails, sorted. Our example: ["Ann", "ann@home", "ann@work"], ["Ann", "a.k@uni", "ann@work"], ["Ann", "ak@mail", "a.k@uni"], ["Ann", "ann@x"] → ["Ann", "a.k@uni", "ak@mail", "ann@home", "ann@work"], ["Ann", "ann@x"].

input
accounts: a list of accounts. accounts[i][0] is a name, and the rest of accounts[i] are emails.
returns
The accounts of each person merged into one. Two accounts belong to one person when they share an email, also through other accounts; the same name alone does not make one person. Each person is the name followed by all their emails, each once and in sorted order; the people in any order.
constraints
  • 1 ≤ accounts.length ≤ 50
  • 2 ≤ accounts[i].length ≤ 10
  • accounts[i][0]: 1 to 10 English letters
  • accounts[i][j], j ≥ 1: an email of at most 30 lowercase letters, digits and dots, with one @
  • accounts that share an email have the same name
our 11 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {string[][]} accounts
 * @return {string[][]}
 */
function accountsMerge(accounts) {

}
Ctrl ↵
format
reset

saved in this browser

11 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more union-find problems

Pattern “Union-Find” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.