Skip to content
BytePatterns

Accounts Merge By Email

HardUnion-Find#union-find#hash-map~45m

Problem

Each account is a name followed by one or more email addresses. Two accounts belong to the same person when they share at least one email, and that sharing is transitive: A shares with B and B with C means all three are one person. Merge them, and return each person as their name followed by all their emails in sorted order. Different people may have the same name.

Examples

Input:  [["Jo", "a@x", "b@x"], ["Jo", "b@x", "c@x"], ["Kim", "d@x"]]
Output: [["Jo", "a@x", "b@x", "c@x"], ["Kim", "d@x"]]
Why:    the two Jo accounts share b@x, so they are one person
Input:  [["Jo", "a@x"], ["Jo", "z@x"]]
Output: [["Jo", "a@x"], ["Jo", "z@x"]]
Why:    the same name with no shared email is two different people
Input:  [["Kim", "d@x"]]
Output: [["Kim", "d@x"]]
Why:    edge case, a single account merges with nothing

Hints

0 / 3

Stuck on the idea rather than the code? Union by Rank or Size covers it.