Accounts Merge – Solution & Complexity
Solution Walkthrough
Step 1: See the connectivity pattern
- If two rows share an email, they belong to the same connected component.
- The overlap can be indirect, so you need component merging rather than only pairwise merging.
Step 2: Brute-force baseline
- Compare every pair of rows to see whether they share any email, then repeatedly merge overlapping groups.
- That repeated scanning is much too slow once many accounts and emails exist.
Step 3: Union rows by shared emails
- Map each email to the first row that contained it.
- When the same email appears again, union the current row with the previous owner row.
Step 4: Final solution (all languages)
Union-find builds connected account components, then a deterministic sort finishes the output contract.
Step 5: Complexity summary
- Union-find work is effectively near-linear in the number of email occurrences.
- Sorting the merged email lists dominates the final deterministic formatting cost.