721. Accounts Merge

https://leetcode.com/problems/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"]]
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].
  • ---

    Intuition

    Need to connect various lists together => Union find

    Initialize each list's parent to itself

    Standard find function with path compression

        while (u != parent[u]) {

            parent[u] = parent[parent[u]];

            u = parent[u];

        }

        return u;

    --

    Union is slightly different, we need to unionize lists if the emails share the same parent (i.e., list)

    Maintain a map of email to List ID (parent)

    if (map.containsKey(email)) { // unionize lists

        int parentU = find(map.get(email)); // list from pre existing mapping

        int parentV = find(i); // parent of current list

        parent[parentU] = parentV;

    } else {

        map.put(email, i);

    }

    ---

    Preprocess the email to listID mapping to prep the output

    for (Map.Entry<String, Integer> entry: map.entrySet()) {

        listID = entry.getValue();

        email = entry.getKey();

        root = find(listID)); // ** key step, do not put entry in ret based on listID directly, use its root **/

        ret.putIfAbsent(root, new TreeSet<String>());

        ret.get(root).add(email);

    }

    ---


    class Solution {
    int[] parents;
    public List<List<String>> accountsMerge(List<List<String>> accounts) {
    List<List<String>> ans = new ArrayList<List<String>>();
    if (accounts == null || accounts.size() == 0) {
    return ans;
    }
    parents = new int[accounts.size()];
    for (int i = 0; i < parents.length; i++) {
    parents[i] = i;
    }
    Map<String, Integer> map = new HashMap<String, Integer>();
    for (int i = 0; i < accounts.size(); i++) {
    for (int j = 1; j < accounts.get(i).size(); j++) {
    String email = accounts.get(i).get(j);
    // unionize lists
    if (map.containsKey(email)) {
    int parentU = find(map.get(email));
    int parentV = find(i);
    parents[parentV] = parentU;
    } else {
    map.put(email, i);
    }
    }
    }
    Map<Integer, TreeSet<String>> ret = new HashMap<Integer, TreeSet<String>>();
    for (Map.Entry<String, Integer> entry: map.entrySet()) {
    int listID = entry.getValue();
    int root = find(listID);
    String email = entry.getKey();
    ret.putIfAbsent(root, new TreeSet<String>());
    ret.get(root).add(email);
    }
    for (Map.Entry<Integer, TreeSet<String>> entry: ret.entrySet()) {
    List<String> list = new ArrayList<String>();
    list.add(accounts.get(entry.getKey()).get(0));
    list.addAll(entry.getValue());
    ans.add(list);
    }
    return ans;
    }
    private int find(int u) {
    while (parents[u] != u) {
    parents[u] = parents[parents[u]];
    u = parents[u];
    }
    return u;
    }
    }