Coding · must-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix

Accounts Merge

mediumgraphunion-finddfs

Problem

You are given a list of account records. Each record is a list of strings whose first entry is a person's display name and whose remaining entries are email addresses that belong to that account.

Two records belong to the same person if they share at least one email address, and this relation is transitive: if A shares an email with B and B shares one with C, then A, B, and C are all the same person. Two people can have the same display name; that alone does not merge them.

Merge the records and return one list per person, formatted as the name followed by that person's distinct emails in sorted (ASCII) order. The order of the people in the output does not matter.

  • Up to a few thousand records; each holds a name plus between one and a dozen emails.
  • Names and emails are short ASCII strings (a few dozen characters at most).
  • Every record has at least one email, and all records that end up merged carry the same name.

Examples

Hints

  1. Think of each email as a node. What connects two nodes?
  2. The answer is one group per connected component. Which structure finds components incrementally as you read records?
  3. Union-find keyed by email (or by account index); then group emails by their root and sort each group.

Last reviewed 8 September 2026