LeetCode 721 Accounts Merge - Why Naive Fails

The trap

Compare every pair of accounts and check if they share any email.

With nn accounts and mm emails each, checking all pairs is O(n2m2)O(n^2 \cdot m^2). Merging chains of connected accounts adds more complexity.

Can you group emails that belong to the same person more efficiently?