mediumUnion FindHash TableUnion Find

Accounts Merge

mediumTime: O(n * m * α(n*m))Space: O(n * m)

Recognize the pattern

merge accounts with same emailemails link accountsgroup by connectivity

Brute force idea

The naive version of Accounts Merge sounds like this: For each pair of accounts, check for shared emails. Quadratic comparison of all account pairs. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

Better approach

The deeper shift in Accounts Merge is this: Union-Find on account indices. Map each email to the first account that owns it. When an email appears in a second account, union those two accounts. Then group emails by their root account. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

Key invariant

At the center of Accounts Merge is one steady idea: Two accounts belong to the same person if they share any email. Union-Find transitively merges all accounts connected through shared emails into the same set. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Watch out for

The trap in Accounts Merge usually looks like this: Unioning by email instead of by account — emails are the edges, accounts are the nodes. Map emails to account indices, then union the account indices. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Union Find Pattern