Each account row starts with a name followed by one or more email addresses: [name, email1, email2, ...].
Two rows belong to the same person if they share any email address, directly or through a chain of overlaps. Merge all connected rows.
For this judge, keep the output deterministic:
(name, firstEmail) ascending.Input / output
accounts: string[][]string[][] where each row is [name, sortedEmail1, sortedEmail2, ...]Examples
accounts = [["John","johnsmith@mail.com","john_newyork@mail.com"],["John","johnsmith@mail.com","john00@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]] returns [["John","john00@mail.com","john_newyork@mail.com","johnsmith@mail.com"],["John","johnnybravo@mail.com"],["Mary","mary@mail.com"]].
The first two John rows merge because they share johnsmith@mail.com.accounts = [["Alex","a@mail.com"],["Alex","b@mail.com"],["Alex","a@mail.com","c@mail.com"]] returns [["Alex","a@mail.com","c@mail.com"],["Alex","b@mail.com"]].
Only the rows connected through a@mail.com merge.accounts = [["Eve","eve@mail.com","eve2@mail.com"],["Eve","eve2@mail.com","eve3@mail.com"]] returns [["Eve","eve2@mail.com","eve3@mail.com","eve@mail.com"]].
Email overlap can connect more than two rows.Constraints
1 <= accounts.length <= 10002 <= accounts[i].length <= 10Edge cases
Target complexity
Hints
Follow-up How would you solve the same problem with a graph traversal over emails instead of union-find?