← DiffPush

Accounts Merge

Standard Bar Graphs · MST Problems O(N * M α(N) + E log E) · O(N * M)

Consolidating the Customer Identity Cards

A bank's onboarding system holds identity cards, each listing a name plus that card's email addresses. Cards belong to the same customer whenever they share even one email; shared names prove nothing. Compliance wants one consolidated card per customer — name first, then every distinct email sorted — regardless of how many raw cards fed it.

Input: A list accounts where accounts[i] is [name, email1, email2, ...].

Output: Return the merged accounts: each begins with the name followed by that person's emails in sorted order; the list order itself is free.

Constraints

Examples

Example 1

Input: {"accounts":[["John","johnsmith@mail.com","john00@mail.com"],["John","johnnybravo@mail.com"],["John","johnsmith@mail.com","john_newyork@mail.com"],["Mary","mary@mail.com"]]}
Output: [["John","john00@mail.com","john_newyork@mail.com","johnsmith@mail.com"],["John","johnnybravo@mail.com"],["Mary","mary@mail.com"]]
The first and third John cards share an email and merge; the second John stays separate despite the name.

Example 2

Input: {"accounts":[["Gabe","gabe0@x.com","gabe1@x.com"],["Kevin","kevin@x.com"],["Gabe","gabe1@x.com","gabe2@x.com"]]}
Output: [["Gabe","gabe0@x.com","gabe1@x.com","gabe2@x.com"],["Kevin","kevin@x.com"]]
A shared middle email chains the two Gabe cards into one sorted identity.

Solve this in your browser →

Also on LeetCode ↗