<p>Given a list of <code>accounts</code> where each element <code>accounts[i]</code> is a list of strings, where the first element <code>accounts[i][0]</code> is a name, and the rest of the elements are <strong>emails</strong> representing emails of the account.</p>

<p>Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.</p>

<p>After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails <strong>in sorted order</strong>. The accounts themselves can be returned in <strong>any order</strong>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> accounts = [[&quot;John&quot;,&quot;johnsmith@mail.com&quot;,&quot;john_newyork@mail.com&quot;],[&quot;John&quot;,&quot;johnsmith@mail.com&quot;,&quot;john00@mail.com&quot;],[&quot;Mary&quot;,&quot;mary@mail.com&quot;],[&quot;John&quot;,&quot;johnnybravo@mail.com&quot;]]
<strong>Output:</strong> [[&quot;John&quot;,&quot;john00@mail.com&quot;,&quot;john_newyork@mail.com&quot;,&quot;johnsmith@mail.com&quot;],[&quot;Mary&quot;,&quot;mary@mail.com&quot;],[&quot;John&quot;,&quot;johnnybravo@mail.com&quot;]]
<strong>Explanation:</strong>
The first and second John&#39;s are the same person as they have the common email &quot;johnsmith@mail.com&quot;.
The third John and Mary are different people as none of their email addresses are used by other accounts.
We could return these lists in any order, for example the answer [[&#39;Mary&#39;, &#39;mary@mail.com&#39;], [&#39;John&#39;, &#39;johnnybravo@mail.com&#39;], 
[&#39;John&#39;, &#39;john00@mail.com&#39;, &#39;john_newyork@mail.com&#39;, &#39;johnsmith@mail.com&#39;]] would still be accepted.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> accounts = [[&quot;Gabe&quot;,&quot;Gabe0@m.co&quot;,&quot;Gabe3@m.co&quot;,&quot;Gabe1@m.co&quot;],[&quot;Kevin&quot;,&quot;Kevin3@m.co&quot;,&quot;Kevin5@m.co&quot;,&quot;Kevin0@m.co&quot;],[&quot;Ethan&quot;,&quot;Ethan5@m.co&quot;,&quot;Ethan4@m.co&quot;,&quot;Ethan0@m.co&quot;],[&quot;Hanzo&quot;,&quot;Hanzo3@m.co&quot;,&quot;Hanzo1@m.co&quot;,&quot;Hanzo0@m.co&quot;],[&quot;Fern&quot;,&quot;Fern5@m.co&quot;,&quot;Fern1@m.co&quot;,&quot;Fern0@m.co&quot;]]
<strong>Output:</strong> [[&quot;Ethan&quot;,&quot;Ethan0@m.co&quot;,&quot;Ethan4@m.co&quot;,&quot;Ethan5@m.co&quot;],[&quot;Gabe&quot;,&quot;Gabe0@m.co&quot;,&quot;Gabe1@m.co&quot;,&quot;Gabe3@m.co&quot;],[&quot;Hanzo&quot;,&quot;Hanzo0@m.co&quot;,&quot;Hanzo1@m.co&quot;,&quot;Hanzo3@m.co&quot;],[&quot;Kevin&quot;,&quot;Kevin0@m.co&quot;,&quot;Kevin3@m.co&quot;,&quot;Kevin5@m.co&quot;],[&quot;Fern&quot;,&quot;Fern0@m.co&quot;,&quot;Fern1@m.co&quot;,&quot;Fern5@m.co&quot;]]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= accounts.length &lt;= 1000</code></li>
	<li><code>2 &lt;= accounts[i].length &lt;= 10</code></li>
	<li><code>1 &lt;= accounts[i][j].length &lt;= 30</code></li>
	<li><code>accounts[i][0]</code> consists of English letters.</li>
	<li><code>accounts[i][j] (for j &gt; 0)</code> is a valid email.</li>
</ul>

# 1. name is not unique, but email is unique; 
# 2. email like node in the graph,  while the account build up the connection of node
# 3. Graph:  account1 --> email1 --> account3 --> email2
#.                    --> email2 --> account2 
#                     --> email3 --> account3


#'''
# this is a UF problem, to union the accounts
# accounts are connected throught intersected emails
# build up the model: account are nodes,  emails are lines, build them up like a graph. 

from collections import defaultdict

# use DFS for merge and grouping
# strategy: 
# 1.create the connection Graph/structure
# 2.dfs for each connected group/cohort

# key is not the user name!!
class Solution:
    def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:          
        email2accounts = defaultdict(list) # {email:[accounts with this email]}
        for idx, emails in enumerate(accounts):
            for email in emails[1:]: 
                email2accounts[email].append(idx)
                
        # DFS code for traversing accounts.
        def dfs(acc_idx, emails):
            if visited[acc_idx]: return
            visited[acc_idx] = True
            
            # range from 1, so skipped the name, only process the email. 
            for em_idx in range(1, len(accounts[acc_idx])): 
                email = accounts[acc_idx][em_idx]
                emails.add(email)
                # for the those connected emails
                for account in email2accounts[email]:
                    dfs(account, emails)
                    
        visited = [False] * len(accounts)
        res = []
                        
        # Perform DFS for accounts and add to results.
        for acc_idx, acc in enumerate(accounts):
            if visited[acc_idx]: continue # this step is need to avoid duplicate visiting
                
            name, emails = acc[0], set()  
            # we use an emails set here to pass results of the group back without accumuate the results during backtracking
            dfs(acc_idx, emails) # emails here is for return in this dfs
            res.append([name] + list(sorted(emails))) # involve set sorting
            
        return res
        
#'''
    
'''
# not a tpyical solution, but BFS,  it turns to a graph of email connections. 
class Solution(object):
    def accountsMerge(self, accounts):
        em_to_name = {}
        graph = collections.defaultdict(set)
        for acc in accounts:
            name = acc[0]
            for email in acc[1:]:
                graph[acc[1]].add(email)
                graph[email].add(acc[1])
                em_to_name[email] = name

        seen = set()
        ans = []
        for email in graph:
            if email not in seen:
                seen.add(email)
                stack = [email]
                component = []
                while stack:
                    node = stack.pop()
                    component.append(node)
                    for nei in graph[node]:
                        if nei not in seen:
                            seen.add(nei)
                            stack.append(nei)
                ans.append([em_to_name[email]] + sorted(component))
        return ans
'''
    
    
'''
class UnionFind:
    def __init__(self, n):
        #self.parent = [i for i in range(n)]
        self.parent = [*range(n)]
        self.size = [1] * n
        
    def find(self, x):
        if x != self.parent[x]:
            self.parent[x] = self.find(self.parent[x]) # Path compression
        return self.parent[x]
    
    def union(self, u, v):
        pu, pv = self.find(u), self.find(v)
        if pu == pv: return False  # Return False if u and v are already union
        if self.size[pu] > self.size[pv]: # Union by larger size
            self.size[pu] += self.size[pv]
            self.parent[pv] = pu
        else:
            self.size[pv] += self.size[pu]
            self.parent[pu] = pv
        return True

class Solution(object):
    def accountsMerge(self, accounts):
        uf = UnionFind(10000)
        
        map_email_id = {}
        map_id_email = {}
        map_email_name = {}
        id = 0
        for acc in accounts:
            name = acc[0]
            for email in acc[1:]:
                map_email_name[email] = name
                if email not in map_email_id:
                    map_email_id[email] = id
                    map_id_email[id] = email
                    id += 1
                uf.union(map_email_id[acc[1]], map_email_id[email]) # union 1st email and ith emails -> union emails in same account together
        
        
        # after merging, go through all emails finally, through find to locate the parent, which is the group id indeed, 
        # with group, we can further use set to filter out duplicates, and further set the filter out results. 
        merged_emails = defaultdict(set)
        for _id in range(id):
            merged_emails[uf.find(_id)].add(map_id_email[_id])
            
        ans = []
        for (_id, emails) in merged_emails.items():
            name = map_email_name[map_id_email[_id]]
            ans.append([name] + list(sorted(emails)))
        return ans

'''

from collections import defaultdict

class Solution:
    def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:   

        email2accounts = defaultdict(set)
        for acc_idx, account in enumerate(accounts): 
            for email in account[1:]: 
                email2accounts[email].add(acc_idx)

        visited = [False] * len(accounts)

        def dfs(acc_idx, email_set):
            emails = accounts[acc_idx][1:]
            email_set.update(emails)
            visited[acc_idx] = True 

            for email in emails: 
                con_accounts = email2accounts[email]
                for idx in con_accounts: 
                    if not visited[idx]: 
                        dfs(idx, email_set)

        res = []
        for acc_idx, account in enumerate(accounts): 
            if visited[acc_idx]:
                continue

            name = account[0]
            email_set = set()

            dfs(acc_idx, email_set)

            group_lst = [name] + list(sorted(email_set))

            res.append(group_lst)


        return res

25300