Accounts Merge
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Union Find.
Accounts Merge
Given a list of accounts where each element
accounts[i] is a list of strings, the first element accounts[i][0] is a name, and the rest are emails. Merge accounts belonging to the same person. Two accounts belong to the same person if there is some common email to both accounts.Examples
Input: accounts = [["John","a@m.com","b@m.com"],["John","c@m.com","a@m.com"],["Mary","d@m.com"]]
Output: [["John","a@m.com","b@m.com","c@m.com"],["Mary","d@m.com"]]
Approach 1
Level I: DFS (Graph of Emails)
Intuition
Build an adjacency list where each email is a node and edges connect emails within the same account. Use DFS to find connected components of emails.
⏱ O(N \cdot K \log(N \cdot K))💾 O(N \cdot K)
Detailed Dry Run
Account 1: {a, b}. Account 2: {c, a}. Graph: a-b, c-a. Component: {a, b, c}. Sort and add name 'John'.
Approach 2
Level III: Union-Find (Email Mapping)
Intuition
Use DSU to union all emails within an account. After processing all accounts, group emails by their root parent, sort them, and format the output.
⏱ O(N \cdot K \cdot \alpha(N \cdot K))💾 O(N \cdot K)
Detailed Dry Run
Initial: {a:a, b:b, c:c}. Account 1: Union(a, b) -> {a:b, b:b}. Account 2: Union(c, a) -> {c:b, a:b}. All point to 'b'.
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.