Accounts Merge solution explained

To merge accounts that share an email, treat every email as a node and connect all the emails that appear in the same account; each connected group is one person. Union-find does this by joining each account's emails to its first email, and a DFS over an email graph works just as well. Then collect each group, sort its emails, and put the owner's name in front. With N emails in total, the work is O(N log N), dominated by sorting the emails in each group.

By Published 8 min read

The problem in our own words

You are given a list of accounts. Each account is a list whose first item is a person's name and whose other items are email addresses. Any two accounts that have at least one email in common belong to the same person, and that relationship carries through: if account 1 shares an email with account 2, and account 2 shares one with account 3, all three are one person. Accounts with the same name but no shared emails may be different people. Return one entry per person: the name, then all of that person's emails without duplicates, sorted. The order of the entries does not matter. Every account has at least one email, and an email always belongs to one name.

Five accounts made up for this page
#Account
1Rosa: rosa@a.test, rp@b.test
2Rosa: rosa.m@c.test
3Ivo: ivo@a.test
4Rosa: rp@b.test, rosa.m@c.test
5Rosa: r.other@d.test
Five accounts made up for this page. Scroll sideways on a small screen.

Account 4 shares rp@b.test with account 1 and rosa.m@c.test with account 2, so 1, 2 and 4 are one Rosa with three emails: rosa.m@c.test, rosa@a.test, rp@b.test (sorted by character code, so the dot comes before the @). Account 5 is a second Rosa, because none of its emails appear elsewhere. Ivo stands alone. Notice that accounts 1 and 2 share nothing directly; only account 4, which comes later in the list, ties them together.

What the interviewer is looking for

The question tests whether you see a connectivity problem in a list of records. Merging by name is the trap, and a single pass of pairwise merging misses links that only appear later, as accounts 1 and 2 show. Interviewers expect union-find or a graph search, a clear choice of what the nodes are (emails, not accounts or names), and care with duplicates and sorting. It is also a realistic task: deduplicating customer records looks a lot like this.

Brute force: merge until nothing changes

Keep a list of groups, each a name and a set of emails. Look for any two groups whose sets intersect, merge them, and start again. Stop when a full scan finds nothing to merge. Each merge needs up to O(n²) set intersections over n accounts, and there can be up to n - 1 merges, so this is slow, but it is obviously correct and makes a good reference for testing.

def merge_accounts_brute(accounts):
    groups = [[acc[0], set(acc[1:])] for acc in accounts]
    changed = True
    while changed:                       # keep merging any two groups that share an email
        changed = False
        for i in range(len(groups)):
            for j in range(i + 1, len(groups)):
                if groups[i][1] & groups[j][1]:
                    groups[i][1] |= groups[j][1]
                    del groups[j]
                    changed = True
                    break
            if changed:
                break
    return [[name] + sorted(emails) for name, emails in groups]
Repeat pairwise merges until a full pass changes nothing.

Union-find over emails

Give each email its own set. For each account, join every email in it to the account's first email; that is enough to put the whole account in one set, and any email shared with another account joins the two sets. Record which name each email belongs to. After all accounts are processed, group the emails by their root, sort each group and prefix it with the name of any email in it.

from collections import defaultdict


def merge_accounts(accounts):
    parent = {}

    def find(x):
        root = x
        while parent[root] != root:
            root = parent[root]
        while parent[x] != root:          # point the whole path at the root
            parent[x], x = root, parent[x]
        return root

    owner = {}                            # email -> name on the account it came from
    for acc in accounts:
        name, first = acc[0], acc[1]
        for email in acc[1:]:
            if email not in parent:
                parent[email] = email
            owner[email] = name
            parent[find(email)] = find(first)     # join every email to the first one

    groups = defaultdict(list)
    for email in parent:
        groups[find(email)].append(email)
    return [[owner[root]] + sorted(emails) for root, emails in groups.items()]
Union-find keyed by email, with an iterative find. Near-linear before sorting.

The find walks up to the root, then makes a second pass that points every node on the way straight at it. Doing it in a loop instead of recursion keeps long chains of emails from hitting Python's recursion limit. The owner map can hold the name from any account, since an email always belongs to one name.

DFS over an email graph

The other standard answer builds the graph explicitly. Each email is a node, and each account adds an edge from its first email to every other one. A star per account is enough; you do not need every pair. Then run a search from each unvisited email and collect what it reaches. An explicit stack keeps it iterative.

function accountsMerge(accounts) {
  const graph = new Map();   // email -> neighbouring emails
  const owner = new Map();   // email -> account name
  const link = (a, b) => {
    if (!graph.has(a)) graph.set(a, []);
    if (!graph.has(b)) graph.set(b, []);
    if (a !== b) {
      graph.get(a).push(b);
      graph.get(b).push(a);
    }
  };
  for (const [name, first, ...rest] of accounts) {
    owner.set(first, name);
    link(first, first);
    for (const email of rest) {
      owner.set(email, name);
      link(first, email);
    }
  }

  const seen = new Set();
  const result = [];
  for (const start of graph.keys()) {
    if (seen.has(start)) continue;
    seen.add(start);
    const stack = [start];
    const emails = [];
    while (stack.length > 0) {
      const email = stack.pop();
      emails.push(email);
      for (const next of graph.get(email)) {
        if (!seen.has(next)) {
          seen.add(next);
          stack.push(next);
        }
      }
    }
    emails.sort();
    result.push([owner.get(start), ...emails]);
  }
  return result;
}
Star edges per account, then an iterative DFS for each component.

The self-link for the first email matters when an account has only one email: without it that email would never become a node, and the person would vanish from the output. The default JavaScript sort compares strings by UTF-16 code units, which is the order this problem expects for plain ASCII addresses.

Complexity

n accounts, N emails in total across all accounts
ApproachTimeExtra space
Merge until nothing changesPolynomial in n and N, well above quadraticO(N)
Union-find on emails, then sort each groupO(N α(N)) to group with union by size, O(N log N) with the sortsO(N)
DFS on the email graph, then sortO(N) to build and search, O(N log N) with the sortsO(N)
n accounts, N emails in total across all accounts. Scroll sideways on a small screen.

Both fast versions also hash every email string, so strictly the cost scales with the total length of the emails too. The union-find above compresses paths but does not union by size; that keeps the code short and still runs fast, and you can mention the extra step if asked about worst cases.

Edge cases

  • Two different people with the same name: they stay separate unless an email links them.
  • The same email listed twice in one account: the output should list it once.
  • An account with a single email.
  • A chain where the linking account appears last in the input.
  • Every account belonging to one person, or every account belonging to a different person.

Mistakes

  • Grouping by name.
  • Making accounts the nodes and comparing every pair of accounts, which is slow and still needs transitive merging.
  • Connecting every pair of emails inside an account, which is quadratic per account for no gain.
  • Forgetting to deduplicate, or forgetting to sort the emails.
  • Dropping single-email accounts in the graph version.
  • Recursive find or DFS in Python on inputs that can form long chains.

How to explain it out loud

Fictional example

Picking the nodes
Candidate
Names can repeat between people, so the email is the real identity. I'll make each email a node.
Candidate
Every account says its emails belong together, so I'll union each email with the first email of its account. Shared emails then link accounts automatically, even through a chain.
Interviewer
How do you build the output?
Candidate
Group emails by their root, sort each group and put the owner's name in front. Grouping is close to linear in the number of emails, and sorting makes it N log N overall.

Evaluate Division uses the same union-find with a weight on each link. Number of Islands finds connected components on a grid instead of a list of records. Swim in Rising Water can be solved by adding cells to a union-find in height order, and topological sort is the next graph technique to learn after components.

Going over it with Natively

To check your grouping logic, you can give Natively a screenshot of the problem on Mac or Windows and read a suggested approach and code in its overlay, then compare where you put the union calls. When you practice out loud, the transcript it keeps lets you confirm you flagged the same-name trap before writing code. The AI interview assistant page explains how it works.

Questions people ask

How do you solve Accounts Merge?

Make each email a node and connect every email in an account to that account's first email, with union-find or a graph. Each connected group is one person: sort its emails and put the name in front.

Why can't you merge accounts by name?

Different people can share a name. Only a shared email proves two accounts belong to the same person.

What is the time complexity of Accounts Merge?

Grouping is close to linear in the total number of emails N with union-find or DFS. Sorting each group's emails makes the whole solution O(N log N).

Should Accounts Merge use union-find or DFS?

Either works. Union-find needs no explicit graph and handles links that appear later naturally; DFS on a star-shaped email graph is just as fast. Make either one iterative in Python.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP