712507. Account Merge

Hard

Account Merge

Slug: account-merge Difficulty: Hard Id: 712507 Topic Tags: Arrays, Hash, DFS, Graph, union-find, Data Structures, Algorithms

Summary

The Account Merge problem involves merging similar accounts in a social network. Given a list of account pairs and their corresponding email addresses, the task is to merge these accounts into a single account if they have matching email addresses. This process should be efficient, as it's crucial for maintaining data consistency and minimizing user confusion.

Detailed Explanation

The solution to this problem involves implementing a union-find algorithm, which is used to group similar accounts together. We will use an array to keep track of the parent node for each account and another array to store the size of each component (i.e., the number of accounts in each group).

Here's a step-by-step breakdown of the solution:

  1. Initialize two arrays: parent and size. The parent array will store the parent node for each account, and the size array will keep track of the size of each component.
  2. Iterate through the list of account pairs. For each pair, check if the email addresses match.
  3. If the email addresses match, merge the two accounts using a union operation. This involves updating the parent node for one of the accounts to point to the other account.
  4. After processing all the account pairs, iterate through the parent array and group the accounts based on their parent nodes.

Time complexity: O(n), where n is the number of account pairs. Space complexity: O(n), as we need to store the parent node and size for each account.

Optimized Solutions

Here are optimized solutions in various programming languages:

Java

View on GeeksforGeeks
import java.util.*;

class Solution {
    public List<String> accountsMerge(int[][] accounts, int[][] friends) {
        UnionFind uf = new UnionFind(accounts.length);
        Map<Integer, Integer> parent = new HashMap<>();
        Map<Integer, Integer> size = new HashMap<>();

        for (int[] friend : friends) {
            uf.union(friend[0], friend[1]);
        }

        List<String> result = new ArrayList<>();
        Map<Integer, List<String>> emailToName = new HashMap<>();

        for (int i = 0; i < accounts.length; i++) {
            parent.put(i, i);
            size.put(i, 1);
        }

        for (int[] account : accounts) {
            int id = account[0];
            String name = account[1];
            for (String email : account.subarray(2)) {
                uf.union(id, Integer.parseInt(email.split("@")[1]));
                parent.put(Integer.parseInt(email.split("@")[1]), id);
                size.put(id, size.getOrDefault(id, 0) + 1);
            }
        }

        Set<Integer> roots = new HashSet<>();
        for (int i = 0; i < accounts.length; i++) {
            int root = uf.find(i);
            if (!roots.add(root)) {
                continue;
            }
            List<String> emails = new ArrayList<>();
            for (int j = 0; j < accounts.length; j++) {
                if (uf.find(j) == root) {
                    String email = "";
                    for (String accEmail : accounts[j].subarray(2)) {
                        email += accEmail + " ";
                    }
                    emails.add(name + " " + email);
                }
            }
            result.addAll(emails);
        }

        return result;
    }
}

class UnionFind {
    Map<Integer, Integer> parent;

    public UnionFind(int n) {
        parent = new HashMap<>();
        for (int i = 0; i < n; i++) {
            parent.put(i, i);
        }
    }

    public int find(int x) {
        if (parent.get(x) != x) {
            parent.put(x, find(parent.get(x)));
        }
        return parent.get(x);
    }

    public void union(int x, int y) {
        int rootX = find(x);
        int rootY = find(y);

        if (rootX == rootY) {
            return;
        }

        if (size.getOrDefault(rootX, 0) < size.getOrDefault(rootY, 0)) {
            parent.put(rootX, rootY);
        } else {
            parent.put(rootY, rootX);
        }
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.