# 721     Accounts Merge

## 721. [Accounts Merge](https://leetcode.com/problems/accounts-merge/description/)

## 1. Question

Given a list`accounts`, each element`accounts[i]`is a list of strings, where the first element`accounts[i][0]`is aname, and the rest of the elements areemailsrepresenting 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"]]

Explanation:

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.
```

**Note:**

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]`.

## 2. Implementation

**(1) Union Find**

```java
class Solution {
    public List<List<String>> accountsMerge(List<List<String>> accounts) {
        List<List<String>> res = new ArrayList();

        if (accounts == null || accounts.size() == 0) {
            return res;
        }

        UnionFind uf = new UnionFind(accounts.size());

        Map<String, Integer> emailToUser = new HashMap();

        for (int user = 0; user < accounts.size(); user++) {
            List<String> account = accounts.get(user);

            for (int i = 1; i < account.size(); i++) {
                String email = account.get(i);

                emailToUser.putIfAbsent(email, user);
                uf.union(emailToUser.get(email), emailToUser.get(account.get(1)));
            }
        }

        Map<Integer, List<String>> userToEmails = new HashMap();

        for (String email : emailToUser.keySet()) {
            int user = uf.find(emailToUser.get(email));
            userToEmails.putIfAbsent(user, new ArrayList());
            userToEmails.get(user).add(email);
        }

        for (int user : userToEmails.keySet()) {
            List<String> emails = userToEmails.get(user);
            Collections.sort(emails);
            emails.add(0, accounts.get(user).get(0));
            res.add(emails);
        }
        return res;
    }

    class UnionFind {
        int[] parent;
        int[] size;
        int count;

        public UnionFind(int n) {
            parent = new int[n];
            size = new int[n];
            count = n;

            for (int i = 0; i < n; i++) {
                parent[i] = i;
                size[i] = 1;
            }
        }

        public int find(int node) {
            while (node != parent[node]) {
                node = parent[node];
            }
            return node;
        }

        public void union(int i, int j) {
            int root1 = find(i);
            int root2 = find(j);

            if (root1 == root2) return;

            if (size[root1] < size[root2]) {
                parent[root1] = root2;
                size[root2] += size[root1];
            }
            else {
                parent[root2] = root1;
                size[root1] += size[root2];
            }
            --count;
        }
    }
}
```

## 3. Time & Space Complexity

**(1) Union Find:** 时间复杂度O(mnlogn), m是user个数, n是每个user的email个数，最主要的时间是从userToEmails中, 对每个user的email进行排序，空间复杂度O(mn)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://protegejj.gitbook.io/oj-practices/chapter1/union-find/721-accounts-merge.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
