Introduction
Accounts Merge is a popular Union Find (DSU) problem.
You are given:
- Multiple accounts
- Each account contains a name and emails
- Two accounts belong to the same person if they share at least one email
Goal
Merge all accounts belonging to the same person.
Example
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"]
]
Key Observation
Two accounts should be merged if they share at least one common email.
Therefore:
Emails act as connections between accounts.
If two accounts share an email,they belong to the same connected component.Union Find efficiently groups such accounts.
Algorithm
- Initialize DSU for all accounts.
- Map each email to its account index.
- If an email already exists, union both accounts.
- Group emails using ultimate parent.
- Sort emails inside each component.
- Build final answer.
Dry Run
Input
0 → John → a@mail b@mail1 → John → b@mail c@mail
2 → Mary → d@mail
Processing
b@mail appears in account 0 and account 1Union(0,1)
Parent:
0 → 0
1 → 0
2 → 2
Components
Parent 0:a@mail
b@mail
c@mail
Parent 2:
d@mail
Answer
[["John","a@mail","b@mail","c@mail"],
["Mary","d@mail"]
]
Approach : Union Find (DSU)
Accounts sharing emails belong to the same connected component, so Union Find is used to merge them efficiently.
Practice
Time Complexity: O(N × M × α(N) + E log E)Explanation:
Each email is processed once for Union Find operations.The final emails inside every component are sorted before generating the answer.
Space Complexity: O(N + E)
Explanation:
Extra space is used for the parent array, email mapping,and grouped email storage.