KatInterview

721. Accounts Merge

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to merge user accounts based on shared emails. If two accounts have a common email, they are considered to belong to the same person. The goal is to return a list of merged accounts. For each person, the merged account should consist of their name followed by all their unique emails, sorted alphabetically. This problem is a classic example of finding connected components in a graph. We can model the emails as nodes (vertices) and create an edge between two emails if they appear in the same initial account. The merged accounts correspond to the connected components of this graph.

Solution

Accounts Merge in Python

class Solution:
    def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
        parent = {}
        email_to_name = {}

        # DSU find operation with path compression
        def find(s):
            if parent[s] == s:
                return s
            parent[s] = find(parent[s])
            return parent[s]

        # DSU union operation
        def union(s1, s2):
            root1 = find(s1)
            root2 = find(s2)
            if root1 != root2:
                # A simple union, could be optimized with union by size/rank
                parent[root2] = root1

        # Step 1: Initialize DSU and email_to_name map
        for account in accounts:
            name = account[0]
            for i in range(1, len(account)):
                email = account[i]
                if email not in parent:
                    parent[email] = email
                email_to_name[email] = name

        # Step 2: Union emails in the same account
        for account in accounts:
            first_email = account[1]
            for i in range(2, len(account)):
                union(first_email, account[i])

        # Step 3: Group emails by their root
        merged_accounts = {}
        for email in email_to_name:
            root = find(email)
            if root not in merged_accounts:
                merged_accounts[root] = []
            merged_accounts[root].append(email)

        # Step 4: Format the output
        result = []
        for root, emails in merged_accounts.items():
            # Sort emails
            emails.sort()
            # Prepend name
            merged_account = [email_to_name[root]] + emails
            result.append(merged_account)

        return result

Accounts Merge in Java

class Solution {
    public List<List<String>> accountsMerge(List<List<String>> accounts) {
        Map<String, String> parent = new HashMap<>();
        Map<String, String> emailToName = new HashMap<>();

        // Step 1: Initialize DSU and emailToName map
        for (List<String> account : accounts) {
            String name = account.get(0);
            for (int i = 1; i < account.size(); i++) {
                String email = account.get(i);
                parent.put(email, email); // Each email is its own parent initially
                emailToName.put(email, name);
            }
        }

        // Step 2: Union emails in the same account
        for (List<String> account : accounts) {
            String firstEmail = account.get(1);
            for (int i = 2; i < account.size(); i++) {
                union(firstEmail, account.get(i), parent);
            }
        }

        // Step 3: Group emails by their root
        Map<String, List<String>> mergedAccounts = new HashMap<>();
        for (String email : emailToName.keySet()) {
            String root = find(email, parent);
            mergedAccounts.computeIfAbsent(root, k -> new ArrayList<>()).add(email);
        }

        // Step 4: Format the output
        List<List<String>> result = new ArrayList<>();
        for (Map.Entry<String, List<String>> entry : mergedAccounts.entrySet()) {
            String root = entry.getKey();
            List<String> emails = entry.getValue();
            
            Collections.sort(emails);
            
            List<String> mergedAccount = new LinkedList<>();
            mergedAccount.add(emailToName.get(root)); // Add name first
            mergedAccount.addAll(emails); // Add sorted emails
            
            result.add(mergedAccount);
        }

        return result;
    }

    // DSU find operation with path compression
    private String find(String s, Map<String, String> parent) {
        if (parent.get(s).equals(s)) {
            return s;
        }
        String root = find(parent.get(s), parent);
        parent.put(s, root); // Path compression
        return root;
    }

    // DSU union operation
    private void union(String s1, String s2, Map<String, String> parent) {
        String root1 = find(s1, parent);
        String root2 = find(s2, parent);
        if (!root1.equals(root2)) {
            // A simple union, could be optimized with union by size/rank
            parent.put(root2, root1);
        }
    }
}

Accounts Merge in C++

class Solution {
private:
    // DSU find operation with path compression
    string find(string s, unordered_map<string, string>& parent) {
        if (parent[s] == s) {
            return s;
        }
        return parent[s] = find(parent[s], parent);
    }

    // DSU union operation
    void unite(string s1, string s2, unordered_map<string, string>& parent) {
        string root1 = find(s1, parent);
        string root2 = find(s2, parent);
        if (root1 != root2) {
            // A simple union, could be optimized with union by size/rank
            parent[root2] = root1;
        }
    }

public:
    vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {
        unordered_map<string, string> parent;
        unordered_map<string, string> emailToName;

        // Step 1: Initialize DSU and emailToName map
        for (const auto& account : accounts) {
            string name = account[0];
            for (size_t i = 1; i < account.size(); ++i) {
                string email = account[i];
                if (parent.find(email) == parent.end()) {
                    parent[email] = email;
                }
                emailToName[email] = name;
            }
        }

        // Step 2: Union emails in the same account
        for (const auto& account : accounts) {
            if (account.size() > 2) {
                string firstEmail = account[1];
                for (size_t i = 2; i < account.size(); ++i) {
                    unite(firstEmail, account[i], parent);
                }
            }
        }

        // Step 3: Group emails by their root
        unordered_map<string, vector<string>> mergedAccounts;
        for (auto const& [email, name] : emailToName) {
            string root = find(email, parent);
            mergedAccounts[root].push_back(email);
        }

        // Step 4: Format the output
        vector<vector<string>> result;
        for (auto const& [root, emails] : mergedAccounts) {
            vector<string> mergedAccount;
            // First element is the name
            mergedAccount.push_back(emailToName[root]);
            
            // Sort emails and add them
            vector<string> sortedEmails = emails;
            sort(sortedEmails.begin(), sortedEmails.end());
            mergedAccount.insert(mergedAccount.end(), sortedEmails.begin(), sortedEmails.end());
            
            result.push_back(mergedAccount);
        }

        return result;
    }
};

Accounts Merge in TypeScript

function accountsMerge(accounts: string[][]): string[][] {
    const parent = new Map<string, string>();
    const emailToName = new Map<string, string>();

    // DSU find operation with path compression
    const find = (s: string): string => {
        if (parent.get(s) === s) {
            return s;
        }
        const root = find(parent.get(s)!);
        parent.set(s, root); // Path compression
        return root;
    };

    // DSU union operation
    const union = (s1: string, s2: string): void => {
        const root1 = find(s1);
        const root2 = find(s2);
        if (root1 !== root2) {
            // A simple union, could be optimized with union by size/rank
            parent.set(root2, root1);
        }
    };

    // Step 1: Initialize DSU and emailToName map
    for (const account of accounts) {
        const name = account[0];
        for (let i = 1; i < account.length; i++) {
            const email = account[i];
            if (!parent.has(email)) {
                parent.set(email, email);
            }
            emailToName.set(email, name);
        }
    }

    // Step 2: Union emails in the same account
    for (const account of accounts) {
        if (account.length > 2) {
            const firstEmail = account[1];
            for (let i = 2; i < account.length; i++) {
                union(firstEmail, account[i]);
            }
        }
    }

    // Step 3: Group emails by their root
    const mergedAccounts = new Map<string, string[]>();
    for (const email of emailToName.keys()) {
        const root = find(email);
        if (!mergedAccounts.has(root)) {
            mergedAccounts.set(root, []);
        }
        mergedAccounts.get(root)!.push(email);
    }

    // Step 4: Format the output
    const result: string[][] = [];
    for (const [root, emails] of mergedAccounts.entries()) {
        // Sort emails
        emails.sort();
        // Prepend name
        const mergedAccount = [emailToName.get(root)!, ...emails];
        result.push(mergedAccount);
    }

    return result;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.