I knew union-find was the right tool pretty quickly but fumbled the bookkeeping.
Model the problem as a graph where emails are nodes and accounts are edges, then find connected components using Union-Find or DFS. For each component, collect all emails, sort them, and attach the first username encountered.
Pro tip: Mention that Union-Find with path compression and union by rank gives near O(N α(N)) time, which is optimal for this problem. Also, clarify that the username choice is arbitrary but typically the first account's username in the component is used.
Confirm that accounts sharing any email should be merged, and that the output should have emails sorted and a username (e.g., the first account's username). Ask about input size and whether emails are unique per account.
Use a hash map to map each email to an account index or a Union-Find parent array. For Union-Find, initialize parent for each account and union accounts that share an email.
Iterate through each account and its emails. For each email, if it's seen before, union the current account with the account that first had that email; otherwise, record the email's owner.
After processing, group emails by their root parent. For each group, sort the emails and pick a username (e.g., the first account's username in that group).
State time complexity O(N α(N) + M log M) where N is number of accounts and M total emails, and space O(N + M). Walk through a small example to verify correctness.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.