AlgoFrames

Accounts merge

Standard · Write code · about 20 min

Each string in accounts is a name followed by emails, separated by single spaces, such as "John js@mail.com j00@mail.com". Two accounts belong to the same person when they share at least one email; this links transitively. Accounts with the same name may still be different people.

Return one string per person: the name, then all of that person's emails in sorted order (plain string order), separated by spaces. The people may be listed in any order.

Example 1

Input:

[["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"]

Accounts 0 and 1 share johnsmith@mail.com. Account 3 is another John.

Example 2

Input:

[["Ana a@x.com","Ana b@x.com","Ana b@x.com a@x.com"]]

Output:

["Ana a@x.com b@x.com"]

The third account links the first two.

Constraints

  • 1 ≤ accounts.length ≤ 1000
  • Each account has a name and 1 to 10 emails
  • Accounts that share an email have the same name

Learn the idea first: Union-find applications: connectivity, grouping, redundant edges, a visual lesson.

More Union-find applications: connectivity, grouping, redundant edges problems