 All Problems
Accounts Merge
medium
graph
union find
depth-first search
sorting
google
facebook
amazon

Given a list of accounts where each account is a list of strings where the first element is the account name and the rest are emails, merge accounts belonging to the same person (same email = same person). Return the merged accounts sorted (emails within each account sorted; accounts in any order).

Example:

Input:
4
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

Constraints:

  • 1 ≤ accounts.length ≤ 1000
  • 2 ≤ accounts[i].length ≤ 10
  • 1 ≤ accounts[i][j].length ≤ 30

Input format: First line: number of accounts. Then one account per line: "Name email1 email2 ...".

Output format: Merged accounts, each on one line.

Run to check your code against the sample cases, or submit to run every case