Accounts Merge

medium · union-find, hash-map, dfs

Accounts Merge

Given a list of accounts where each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account.

Now, we want to merge accounts. Two accounts definitely belong to the same person if there is some common email. Note that even if two accounts have the same name, they may belong to different people (as people may have the same name). A person can have any number of accounts initially, but all of their accounts definitely have the same name.

After merging, return the accounts sorted:

  • The emails in each account should be sorted lexicographically
  • The order of accounts can be in any order

Function signature

func AccountsMerge(accounts [][]string) [][]string

Examples

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

Explanation:
- First two "John" accounts share "johnsmith@mail.com", so they merge.
- Third "John" has no shared email, so it stays separate.
- "Mary" is separate.

Example 2:

Input: accounts = [["Alex","alex1@mail.com","alex2@mail.com"],
                   ["Alex","alex3@mail.com","alex1@mail.com"]]

Output: [["Alex","alex1@mail.com","alex2@mail.com","alex3@mail.com"]]

Explanation: alex1@mail.com is shared, so all emails merge into one account.

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

Hints

  1. Use Union-Find where each account is a node.
  2. Map each email to the first account that had it.
  3. If an email appears in multiple accounts, union those accounts.
  4. Finally, group all emails by their root account.

Notes

  • Same name doesn't mean same person; only shared emails do.
  • Emails within each merged account must be sorted alphabetically.
  • Remember to include the name as the first element of each result.
Run tests to see results
No issues detected