Accounts Merge
On this page
Problem statement
You get a list of accounts. Each account is a name followed by one or more email addresses. Two accounts belong to the same person if they share at least one email, and this is transitive: if A shares an email with B and B with C, all three are one person. Merge the accounts and return each person once, as the name followed by all their emails in sorted order. Different people can have the same name; a name alone never links accounts.
This is the most common "union-find in disguise" question. It looks like string handling, but it is really about grouping connected items. Original problem: LeetCode 721.
Example

Input: [["John", "js@x", "jny@x"],
["John", "js@x", "j00@x"],
["Mary", "mary@x"],
["John", "jb@x"]]
Output: [["John", "j00@x", "jny@x", "js@x"],
["Mary", "mary@x"],
["John", "jb@x"]] # groups in any order
(Short email names keep the example readable.)
Constraints (assumed)
- 1 ≤ number of accounts ≤ 1,000; each has 1 to 10 emails, up to 30 characters each.
- Emails are compared exactly as strings.
What this question tests
- Recognizing a connected-components problem when the input doesn't look like a graph.
- Choosing what the nodes are (emails, not accounts or names).
- Implementing union-find, or a graph DFS, cleanly with string keys.
Questions to ask first
- Can two different people have the same name? (Yes, so never merge by name.)
- Is the link transitive? (Yes: A–B and B–C means A, B and C are one person.)
- Does the output need sorted emails? Sorted groups? (Emails sorted inside each group; groups in any order.)
- Are emails case-sensitive? Normalizing case is a reasonable question for real data.
Try it yourself first
You have the full problem. Sketch your answer, then sign up free to read the complete walkthrough.
- The complete design, flow by flow, with pictures
- Deep dives into the hard parts
- What mid, senior and staff candidates are expected to say
- Full company question lists
Free forever. No card needed.