Accounts Merge

medium

You are given a list of accounts, each a comma-joined string "name,email1,email2,...". Two accounts belong to the same person if they share at least one email (names may repeat across different people). Merge them: each merged account is "name,<emails>" where the emails are unique and sorted, and the name is taken from the merged group. Return the list of merged accounts (order does not matter).

(To keep I/O simple each account is a single comma-separated string with no spaces; the group's name is taken from its smallest-index original account.)

Hints

Two accounts merge if they share any email — and merging is transitive.
Model it as connected components: accounts are nodes, a shared email is an edge.
Union accounts through a first-owner-per-email map, then output each group's sorted unique emails.

Common doubts

Comparing every pair is O(N²·emails). Mapping each email to its first owner lets you merge in one pass over the emails.
No — only shared emails link accounts; different people can share a name.
The merged account must list its emails uniquely and in a canonical (sorted) order.

Interview follow-ups

Store name alongside each account index; all accounts in a group share the person, so any (here the smallest-index) name works.
Union-Find with path compression stays near-linear; the sort of emails dominates.

Fun facts

  • LeetCode 721 — a connected-components problem hiding behind string parsing.
  • The 'union through a shared key' trick reappears in most-stones-removed and friend-circle problems.

Asked at

AmazonFacebookGoogle
Frequently Sometimes Occasionally
Example 1
Input: accounts = ["john,a,b", "john,b,c", "mary,d"]
Output: ["john,a,b,c", "mary,d"]
The two john accounts share email b, so they merge; mary is separate.
Example 2
Input: accounts = ["p,e1", "q,e2", "r,e1"]
Output: ["p,e1", "q,e2"]
p and r share e1 and merge (keeping the smaller-index name p); q stands alone.
Constraints

- 1 <= accounts.length <= 1000 - each account has a name and 0+ emails - emails and names contain no spaces

Solve this problem →