TRT
Sign in
mediumAdvancedLeetCode#union-find over keys#group by root

Accounts merge

Merge user accounts that share any email address, by unioning emails and grouping them by root.

The Runtime Theory Team1 min read
Taught inUnion by rank and path compressionPro — members onlyAttaching the smaller tree under the larger keeps trees logarithmically shallow, and pointing every visited node straight at the root flattens them further. Together they make union-find's operations nearly constant time.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inaccounts = [["A", "a@x", "b@x"], ["A", "b@x", "c@x"], ["B", "d@x"]]

out[["A", "a@x", "b@x", "c@x"], ["B", "d@x"]]

inaccounts = [["A", "a@x"], ["A", "b@x"]]

out[["A", "a@x"], ["A", "b@x"]]

inaccounts = [["A", "a@x", "b@x"], ["A", "c@x", "d@x"], ["A", "b@x", "c@x"]]

out[["A", "a@x", "b@x", "c@x", "d@x"]]

Each account is a name followed by email addresses. Two accounts belong to the same person if they share at least one email address. Two accounts with the same name may belong to different people. Merge the accounts and return each person's name followed by their emails in sorted order. The accounts may be returned in any order.

Before you code

The elements here are email addresses, not account indexes. What should be unioned for each account, and how do you get from roots back to groups?

Hints

  1. Map each email to an integer id, or use a dictionary-based union-find keyed by the email itself.
  2. For each account, union every email with the account's first email. Record each email's owner name.
  3. Group emails by find(email), sort each group, and prepend the owner's name.
  4. Notice how the third test case chains two accounts through a third: union-find handles the transitivity for free.

Production & complexity notes

When solving Accounts merge on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Union by rank and path compression to reinforce the underlying pattern.

What it practices

A reusable union-find over arbitrary keys, from Union by rank and path compression.

Not started

Sign in to save your learning progress.

Sign in to save