The Accounts Merge coding problem gives you a list of accounts where each account has a name and a list of emails. The catch? The same person can have multiple accounts, but only if there is at least one common email between them. You need to merge these accounts so that each person has only one consolidated account with all their unique emails sorted alphabetically.
This is a favorite at Microsoft, Meta, and Pinterest because it is a classic Graph connectivity problem. It tests your ability to model real-world data as a graph where emails are nodes and an account connects those nodes. It evaluates your proficiency with Union-Find or DFS/BFS.
The most common approach is the Union-Find interview pattern (Disjoint Set Union). Each email is mapped to an ID. If two emails appear in the same account, you "Union" them. After processing all accounts, all emails belonging to the same person will point to the same root representative. Alternatively, you can use Depth-First Search (DFS) to find connected components in the email graph.
["a@m.com", "b@m.com"]["c@m.com", "b@m.com"]["d@m.com"]Because Account 1 and 2 both share b@m.com, they belong to the same John.
Merged Result:
["a@m.com", "b@m.com", "c@m.com"] (sorted)["d@m.com"]When a problem asks you to "group" or "merge" items based on common relationships, your mind should immediately go to Union-Find. It’s the most efficient way to handle dynamic connectivity in a graph.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Smallest String With Swaps | Medium | Solve | |
| Sentence Similarity II | Medium | Solve | |
| Similar String Groups | Hard | Solve | |
| Regions Cut By Slashes | Medium | Solve | |
| Number of Distinct Islands II | Hard | Solve |