Merge Contact Lists That Share an Email
Implement mergeAccounts
You are given several contact lists, each a list of email codes. Two lists that share at least one code belong to the same person, and the relation is transitive: if list A shares a code with B and B with C, all three are one person. Merge the lists of every person into one sorted list of codes, and return the lists ordered by their smallest code.
Treating every list as a node and joining lists that share a code gives a graph; its connected components are the persons. Union-find finds them efficiently.
Example 1:
Input: accounts = [[5,9,12],[3,7],[12,20,4],[7,15],[30],[9,2]]
Output: [[2,4,5,9,12,20],[3,7,15],[30]]
Example 2:
Input: accounts = [[1],[2],[3]]
Output: [[1],[2],[3]]
Example 3:
Input: accounts = [[4,6],[6,8],[8,4]]
Output: [[4,6,8]]
+ 15 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ accounts.length ≤ 8; accounts[i] lists the email codes (integers 1 … 40) of the i-th account, 1 to 5 distinct codes per account (adjacency-list form of an account → email list) - ●
Two accounts belong to the same person if they have at least one email code in common (directly, or through other accounts): the relation is transitive - ●
A code always belongs to one person (accounts of different people never share a code) - ●
Return one list per person containing all of their email codes in increasing order, with the lists ordered by their first (smallest) code
accounts =