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

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.

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 in sorted order. The accounts themselves can be returned in any order.

&nbsp;
Example 1:

Input: accounts = [["John","johnsmith@mail.com","john_newyork@mail.com"],["John","johnsmith@mail.com","john00@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]
Output: [["John","john00@mail.com","john_newyork@mail.com","johnsmith@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]
Explanation:
The first and second John's are the same person as they have the common email "johnsmith@mail.com".
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 [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'], 
['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.


Example 2:

Input: accounts = [["Gabe","Gabe0@m.co","Gabe3@m.co","Gabe1@m.co"],["Kevin","Kevin3@m.co","Kevin5@m.co","Kevin0@m.co"],["Ethan","Ethan5@m.co","Ethan4@m.co","Ethan0@m.co"],["Hanzo","Hanzo3@m.co","Hanzo1@m.co","Hanzo0@m.co"],["Fern","Fern5@m.co","Fern1@m.co","Fern0@m.co"]]
Output: [["Ethan","Ethan0@m.co","Ethan4@m.co","Ethan5@m.co"],["Gabe","Gabe0@m.co","Gabe1@m.co","Gabe3@m.co"],["Hanzo","Hanzo0@m.co","Hanzo1@m.co","Hanzo3@m.co"],["Kevin","Kevin0@m.co","Kevin3@m.co","Kevin5@m.co"],["Fern","Fern0@m.co","Fern1@m.co","Fern5@m.co"]]


&nbsp;
Constraints:


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


class Solution:
    def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
        def merge(accounts):
            res = []
            ls = []
            for i in range(len(accounts)):
                temp = list(set(accounts[i][1:]))
                temp.sort()
                temp = [accounts[i][0]] + temp
                if i in ls:
                    continue
                for j in range(len(accounts[i:])):
                    s = i+j
                    if i == s:
                        continue
                    if accounts[i][0] != accounts[s][0]:
                        continue
                    temp3 = list(set(accounts[s][1:]))
                    uni = list(set(temp[1:]) | set(temp3))
                    if len(uni) < len(temp[1:]) + len(temp3):
                        temp1 = list(set(temp[1:]) | set(temp3))
                        temp = [temp[0]] + temp1 
                        ls.append(s)
                temp0 = temp[1:]
                temp0.sort()
                temp = [temp[0]]+temp0
                res.append(temp)
            return res
        merged = merge(accounts)
        while merge(merged) != merged:
            merged = merge(merged)

        return merged
class Solution {
    public List<List<String>> accountsMerge(List<List<String>> accounts) {
        
        int l = accounts.size();
        UnionFind uf = new UnionFind(l);
        
        Map<String, Integer> emailToNameId = new HashMap<>();
        
        for(int i=0; i<l; i++) {
            List<String> account = accounts.get(i);
            for(int j=1; j<account.size(); j++) {
                String email = account.get(j);
                int currentNameId = i;
                if (emailToNameId.containsKey(email)) {
                    int oldNameId = emailToNameId.get(email);
                    // Join new and old name ids so that we can know which emails can be merged together. Emails in a single component can be merged together.
                    uf.union(currentNameId, oldNameId);
                } else {
                    emailToNameId.put(email, currentNameId);
                }
            }
        }
        // emailToNameId = {johnnybravo@mail.com=3, johnsmith@mail.com=0, john00@mail.com=1, john_newyork@mail.com=0, mary@mail.com=2}

        // Use TreeSet for alphabetical order. 
        Map<Integer, TreeSet<String>> nameIdToEmails = new HashMap<>();
        for(int i=0; i<l; i++) {
            int root = uf.find(i);
            nameIdToEmails.putIfAbsent(root, new TreeSet<>());
            List<String> account = accounts.get(i);
            List<String> emails = account.subList(1, account.size());
            nameIdToEmails.get(root).addAll(emails);
        }
        // nameIdToEmails = {1=[john00@mail.com, john_newyork@mail.com, johnsmith@mail.com], 2=[mary@mail.com], 3=[johnnybravo@mail.com]}

        List<List<String>> out = new ArrayList<>();
        for(int id : nameIdToEmails.keySet()) {
            String name = accounts.get(id).get(0);
            List<String> emails = new ArrayList<>(nameIdToEmails.get(id));
            emails.add(0, name);
            out.add(emails);
        }
        return out;
    }
    
    class UnionFind {
        int[] parent;
        int[] rank;
        
        UnionFind(int size) {
            parent = new int[size];
            rank = new int[size];
            for(int i=0; i<size; i++) {
                parent[i] = i;
                rank[i] = 1;
            }
        }
        
        public void union(int x, int y) {
            int rootX = find(x);
            int rootY = find(y);
            if (rootX != rootY) {
                if (rank[rootX] > rank[rootY]) {
                    parent[rootY] = rootX;
                } else if (rank[rootX] < rank[rootY]) {
                    parent[rootX] = rootY;
                } else {
                    parent[rootY] = rootX;
                    rank[rootX] += 1;
                }
            }
        }
        
        public int find(int x) {
            if (x == parent[x]) {
                return x;
            }
            return parent[x] = find(parent[x]);
        }
        
        
    }
}
class Solution {
public:
    vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {
        map<string,int>stop;
        map<int,string>name;
        int count=0;
        vector<int>par(1005,0),sz(1005,1);
        for(int i=1;i<=1000;i++)
        {
            par[i]=i;
        }
        function<int(int)> findpar = [&](int a) -> int {
            if(a==par[a])return par[a];
            return par[a]=findpar(par[a]);
        };
        function<void(int,int)> dounion =[&](int a,int b) ->void {
            a=findpar(a);
            b=findpar(b);
            if(a!=b)
            {
                if(sz[a]<sz[b]) swap(a,b);
                par[b]=a;
                sz[a]+=sz[b];
            }
        };
        
        for(auto it:accounts){
            
            int n=it.size();
            vector<int>curpar;
            for(int i=1;i<n;i++)
            {
                if(stop[it[i]])
                    curpar.push_back(stop[it[i]]);
            }
            if(curpar.size()==0) // if no par present 
            {
                count++;
                for(int i=1;i<n;i++)
                {
                    stop[it[i]]=count;
                }
                name[count]=it[0];
            }
            else{ // if par present then do union
                int first=curpar[0];
                for(int i=1;i<n;i++) 
                {
                    stop[it[i]]=first;
                }
                
                for(int j=1;j<curpar.size();j++) // union for all child
                {
                    int id=curpar[j];
                    dounion(first,id);
                }
            }
        }
        
        vector<vector<string>>ans;
        
        for(int i=1;i<=1000;i++)
        {
            vector<string> cur;
            if(findpar(i)==i)
            {
                for(auto it:stop)
                {
                    if(findpar(it.second)==i){
                        cur.push_back(it.first);
                    }
                }
            }
            if(cur.size()>0)
            {
                cur.insert(cur.begin(),name[i]);
                ans.push_back(cur);
            }
        }
        return ans;
    }
};
/**
 * @param {string[][]} accounts
 * @return {string[][]}
 */

var accountsMerge = function(accounts) {

    let graph = {};
    let nameDict = {};

    for (let acc of accounts) {
        let name = acc[0];
        nameDict[acc[1]] = name;
        for (let i=1;i<acc.length;i++) {
            if (!graph[acc[i]]) graph[acc[i]] = new Set();
            nameDict[acc[i]] = name;
            if (i != 1) {
                graph[acc[1]].add(acc[i]);
                graph[acc[i]].add(acc[1]);
            }
        }
    }

    let res = [];
    let visited = new Set();

    let dfs = function (key) {
        visited.add(key);
        let emails = [key];
        graph[key].forEach((e)=>{
            if (!visited.has(e)) {
                emails.push(...dfs(e));
            }
        })

        return emails;
    }

    for (let key in graph) {
        if (!visited.has(key)) {
            let temp = dfs(key);
            temp.sort();
            temp.unshift(nameDict[temp[0]]);
            res.push(temp);
        }
    }

    return res;
};
Accounts Merge