Accounts Merge

Free with account Updated Nov 19, 2026 · 7 min read
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

    The first two John accounts share js@x, so they merge into one John with three emails. Mary stays alone, and the John with jb@x stays separate because that account shares no email with them.
    The first two John accounts share js@x, so they merge into one John with three emails. Mary stays alone, and the John with jb@x stays separate because that account shares no email with them.
    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

    1. Can two different people have the same name? (Yes, so never merge by name.)
    2. Is the link transitive? (Yes: A–B and B–C means A, B and C are one person.)
    3. Does the output need sorted emails? Sorted groups? (Emails sorted inside each group; groups in any order.)
    4. Are emails case-sensitive? Normalizing case is a reasonable question for real data.