Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/721.html

721. Accounts Merge




Given a list accounts, 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 email that is common 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.

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’s are the same person as they have the common email “johnsmith@mail.com”.

The second 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.


  • The length of accounts will be in the range [1, 1000].
  • The length of accounts[i] will be in the range [1, 10].
  • The length of accounts[i][j] will be in the range [1, 30].


Use a map to store each name and the corresponding sets of emails. Loop over accounts. For each account in accounts, obtain the name and the list of emails. Use a set to store the emails. Then obtain the sets of emails of the name from the map. For each previous set, if it has at least one common email with the current set, then add all the emails from the previous set into the current set and remove the previous set. Finally, add the current set to the entry of the name in the map. This is the process of merging accounts.

After the accounts are merged, loop over all the entries of the map. For each name, obtain all the sets. Each set represents an account. Use a list to store the accounts and return.

  • class Solution {
        public List<List<String>> accountsMerge(List<List<String>> accounts) {
            Map<String, List<Set<String>>> map = new HashMap<String, List<Set<String>>>();
            for (List<String> account : accounts) {
                String name = account.get(0);
                int size = account.size();
                Set<String> emails = new HashSet<String>();
                for (int i = 1; i < size; i++)
                List<Set<String>> list = map.getOrDefault(name, new ArrayList<Set<String>>());
                List<Set<String>> loopList = new ArrayList<Set<String>>(list);
                for (Set<String> prevSet : loopList) {
                    Set<String> intersection = new HashSet<String>(prevSet);
                    if (intersection.size() > 0) {
                map.put(name, list);
            List<List<String>> mergedAccounts = new ArrayList<List<String>>();
            Set<String> keySet = map.keySet();
            for (String name : keySet) {
                List<Set<String>> list = map.get(name);
                for (Set<String> set : list) {
                    List<String> accountList = new ArrayList<String>(set);
                    accountList.add(0, name);
            return mergedAccounts;
  • // OJ: https://leetcode.com/problems/accounts-merge/
    // Time: O(NMWlog(NM))
    // Space: O(NMW)
    class UnionFind {
        vector<int> id;
        UnionFind(int n) : id(n) {
            iota(begin(id), end(id), 0);
        int find(int x) {
            return id[x] == x ? x : (id[x] = find(id[x]));
        void connect(int a, int b) {
            id[find(a)] = find(b);
    class Solution {
        vector<vector<string>> accountsMerge(vector<vector<string>>& A) {
            unordered_map<string, int> emailToIndex; // email to the index of the last account entry containing this email
            for (int i = 0; i < A.size(); ++i) {
                for (int j = 1; j < A[i].size(); ++j) emailToIndex[A[i][j]] = i;
            UnionFind uf(A.size());
            for (int i = 0; i < A.size(); ++i) {
                for (int j = 1; j < A[i].size(); ++j) uf.connect(i, emailToIndex[A[i][j]]);
            unordered_map<int, set<string>> idToEmail;
            for (int i = 0; i < A.size(); ++i) {
                auto &st = idToEmail[uf.find(i)];
                for (int j = 1; j < A[i].size(); ++j) st.insert(A[i][j]);
            vector<vector<string>> ans;
            for (auto &[id, emails] : idToEmail) {
                for (auto &email : emails) ans.back().push_back(email);
            return ans;
  • class Solution:
        def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
            def find(x):
                if p[x] != x:
                    p[x] = find(p[x])
                return p[x]
            n = len(accounts)
            p = list(range(n))
            email_id = {}
            for i, account in enumerate(accounts):
                name = account[0]
                for email in account[1:]:
                    if email in email_id:
                        p[find(i)] = find(email_id[email])
                        email_id[email] = i
            mp = defaultdict(set)
            for i, account in enumerate(accounts):
                for email in account[1:]:
            ans = []
            for i, emails in mp.items():
                t = [accounts[i][0]]
            return ans
    class Solution(object):
        def accountsMerge(self, accounts):
            :type accounts: List[List[str]]
            :rtype: List[List[str]]
            n = len(accounts)
            self.par = [x for x in range(n)]
            nameMap = collections.defaultdict(list)
            for i, account in enumerate(accounts):
            for i in range(n):
                for j in nameMap[accounts[i][0]]:
                    if (not self.same(i, j)) and (set(accounts[i][1:]) & set(accounts[j][1:])):
                        self.union(i, j)
            res = [set() for _ in range(n)]
            for i in range(n):
                self.par[i] = self.find(i)
                res[self.par[i]] |= set(accounts[i][1:])
            ans = []
            for i in range(n):
                if self.par[i] == i:
                    person = list()
            return ans
        def find(self, x):
            if x == self.par[x]:
                return self.par[x]
            parent = self.find(self.par[x])
            self.par[x] = parent
            return parent
        def union(self, x, y):
            x = self.find(x)
            y = self.find(y)
            if x == y:
            self.par[x] = y
        def same(self, x, y):
            return self.find(x) == self.find(y)

All Problems

All Solutions