Accounts Merge (LeetCode 721): Solution and Explanation

Medium
Array
Hash Table
String
Depth First Search
Breadth First Search
Union Find
Sorting

Each account is a name followed by some email addresses. Two accounts belong to the same person if they share any email, and this relation chains, so you must merge all connected accounts and output each person's name with their emails in sorted order.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Two people can share a name, so names are useless for merging; only shared emails matter. A brute force would compare every pair of accounts for a common email and merge repeatedly until nothing changes, which gets quadratic or worse because one merge can enable another.

Rephrase it as a graph problem. Treat every email as a node and connect emails that appear in the same account. Then each person is a connected component, and the task becomes finding components and listing their nodes. You could build the graph and run DFS, but union-find fits even better because it merges groups as you read the input.

For each account, union every email with the account's first email. That links everything inside one account into one set, and if an email shows up in a second account, that second account's set gets merged with the first automatically. Afterward, find the root of every email, bucket emails by root, sort each bucket and attach the name, which you recorded per email while scanning.

Approach: Union-find on emails

  1. Create a parent map and a find with path compression that lazily adds unseen emails as their own parent.
  2. Define union(x, y) to attach the root of x under the root of y.
  3. For every account, record email_to_name[email] = name for each email and call union(account[1], email).
  4. Iterate over all emails, compute find(email) and append the email to groups[root].
  5. For each group, sort the emails and prepend the name of any email in the group.
  6. Return the list of merged accounts.

Step-by-step example

accounts = [["John","[email protected]","[email protected]"],["John","[email protected]","[email protected]"],["Mary","[email protected]"],["John","[email protected]"]]
  1. Account 1 unions johnsmith with itself, then unions johnsmith with john_newyork, so johnsmith now points to john_newyork.
  2. Account 2 unions johnsmith with john00. The root of johnsmith is john_newyork, which now points to john00, so all three emails share root john00.
  3. Accounts 3 and 4 each contain a single email, so mary and johnnybravo stay as their own roots.
  4. Grouping by root gives three groups: {johnsmith, john_newyork, john00}, {mary} and {johnnybravo}.
  5. Sorting the first group gives john00, john_newyork, johnsmith (the digit sorts before the underscore, which sorts before s), and the name John is prepended. The output is three accounts: two for John and one for Mary.

Code: Python, Java, C++

1class Solution:
2    def accountsMerge(self, accounts):
3        parent = {}
4        def find(x):
5            if x != parent.setdefault(x, x):
6                parent[x] = find(parent[x])
7            return parent[x]
8        def union(x, y):
9            parent[find(x)] = find(y)
10
11        email_to_name = {}
12        for account in accounts:
13            name = account[0]
14            for email in account[1:]:
15                email_to_name[email] = name
16                union(account[1], email)
17
18        groups = {}
19        for email in email_to_name:
20            root = find(email)
21            groups.setdefault(root, []).append(email)
22
23        return [[email_to_name[emails[0]]] + sorted(emails) for emails in groups.values()]

Time and space complexity

Time

O(N log N)

With N total emails, the unions and finds cost nearly constant amortized time each thanks to path compression, so sorting the emails within groups dominates at O(N log N).

Space

O(N)

The parent map, the email to name map and the groups each store every email once.

Other approaches

Graph plus DFS (time O(N log N), space O(N))

Build an adjacency list linking each account's first email to its other emails, then DFS from every unvisited email to collect a component. Same idea, and some people find it easier to explain than union-find.

Union by account index (time O(N log N), space O(N))

Map each email to the first account index that contained it and union account indices instead of emails. The parent array is smaller and integer-keyed, which can be faster in Java or C++.

Common mistakes

  • Merging accounts by name merges different people called John; only shared emails decide ownership.
  • Unioning only consecutive emails across accounts without connecting each account internally misses chains; every email must be tied to its account's first email.
  • Forgetting to sort the emails in each output group fails the expected format even when the grouping is right.
  • A recursive find without path compression can build long chains, and in Python deep chains also risk hitting the recursion limit.

Frequently asked questions

Why use union-find for accounts merge?

Each person is a connected component of emails, and union-find builds those components incrementally as you scan the accounts. It handles chains like A shares with B and B shares with C without any extra passes.

Can two different people have the same name?

Yes, and that is the main trap. Accounts are only merged when they share an email address, so two Johns with no common email stay separate.

What is the time complexity of accounts merge?

Roughly O(N log N) where N is the total number of emails. Union-find operations are nearly constant amortized, and sorting each person's emails is the dominant cost.

Is DFS or union-find better here?

Both are accepted and have the same complexity. Union-find avoids building an explicit graph, while DFS is sometimes easier to write correctly under interview pressure.