## Wednesday, May 2, 2018

### LeetCode 721 - Accounts Merge

https://leetcode.com/problems/accounts-merge/description/
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].
• Union-Find
https://leetcode.com/problems/accounts-merge/solution/
As in Approach #1, our problem comes down to finding the connected components of a graph. This is a natural fit for a Disjoint Set Union (DSU) structure.
Algorithm
As in Approach #1, draw edges between emails if they occur in the same account. For easier interoperability between our DSU template, we will map each email to some integer index by using emailToID. Then, dsu.find(email) will tell us a unique id representing what component that email is in.
For more information on DSU, please look at Approach #2 in the article here. For brevity, the solutions showcased below do not use union-by-rank.
• Time Complexity: $O(A \log A)$, where $A = \sum a_i$, and $a_i$ is the length of accounts[i]. If we used union-by-rank, this complexity improves to $O(A \alpha(A)) \approx O(A)$, where $\alpha$ is the Inverse-Ackermannfunction.
• Space Complexity: $O(A)$, the space used by our DSU structure.
    public List<List<String>> accountsMerge(List<List<String>> accounts) {
DSU dsu = new DSU();
Map<String, String> emailToName = new HashMap();
Map<String, Integer> emailToID = new HashMap();
int id = 0;
for (List<String> account: accounts) {
String name = "";
for (String email: account) {
if (name == "") {
name = email;
continue;
}
emailToName.put(email, name);
if (!emailToID.containsKey(email)) {
emailToID.put(email, id++);
}
dsu.union(emailToID.get(account.get(1)), emailToID.get(email));
}
}

Map<Integer, List<String>> ans = new HashMap();
for (String email: emailToName.keySet()) {
int index = dsu.find(emailToID.get(email));
}
for (List<String> component: ans.values()) {
Collections.sort(component);
}
return new ArrayList(ans.values());
}
}
class DSU {
int[] parent;
public DSU() {
parent = new int[10001];
for (int i = 0; i <= 10000; ++i)
parent[i] = i;
}
public int find(int x) {
if (parent[x] != x) parent[x] = find(parent[x]);
return parent[x];
}
public void union(int x, int y) {
parent[find(x)] = find(y);
}
1. The key task here is to connect those emails, and this is a perfect use case for union find.
2. to group these emails, each group need to have a representative, or parent.
3. At the beginning, set each email as its own representative.
4. Emails in each account naturally belong to a same group, and should be joined by assigning to the same parent (let's use the parent of first email in that list)
    public List<List<String>> accountsMerge(List<List<String>> acts) {
Map<String, String> owner = new HashMap<>();
Map<String, String> parents = new HashMap<>();
Map<String, TreeSet<String>> unions = new HashMap<>();
for (List<String> a : acts) {
for (int i = 1; i < a.size(); i++) {
parents.put(a.get(i), a.get(i));
owner.put(a.get(i), a.get(0));
}
}
for (List<String> a : acts) {
String p = find(a.get(1), parents);
for (int i = 2; i < a.size(); i++)
parents.put(find(a.get(i), parents), p);
}
for(List<String> a : acts) {
String p = find(a.get(1), parents);
if (!unions.containsKey(p)) unions.put(p, new TreeSet<>());
for (int i = 1; i < a.size(); i++)
}
List<List<String>> res = new ArrayList<>();
for (String p : unions.keySet()) {
List<String> emails = new ArrayList(unions.get(p));
}
return res;
}
private String find(String s, Map<String, String> p) {
return p.get(s) == s ? s : find(p.get(s), p);
}

public List<List<String>> accountsMerge(List<List<String>> accounts) {
UnionFind uf = new UnionFind(accounts);
for (int i = 1; i < accounts.size(); i++) {
int tmp = i;
Set<Integer> groups = uf.getGroup(getEmails(accounts.get(i))).stream().filter(x -> x < tmp)
.collect(Collectors.toSet());
uf.union(groups, i);
}

Map<Integer, PersonEmail> results = new HashMap<>();

System.out.println(uf);
for (int i = 0; i < accounts.size(); i++) {
results.computeIfAbsent(uf.findRoot(i), tmp -> new PersonEmail()).setName(getName(accounts.get(i)))
}

return results.values().stream().map(pe -> {
List<String> list = new ArrayList<>();
return list;
}).collect(Collectors.toList());
}

private static class PersonEmail {
public String name;
public Set<String> emails = new HashSet<>();

public PersonEmail() {
}

return this;
}

public PersonEmail setName(String name) {
this.name = name;
return this;
}
}

private String getName(List<String> account) {
return account == null ? null : account.get(0);
}

private List<String> getEmails(List<String> account) {
return account == null ? new ArrayList<>() : account.subList(1, account.size());
}

private static class UnionFind {
int[] parent;
// TODO make it generic
Map<String, Set<Integer>> emailGroups = new HashMap<>();

int size;

public UnionFind(List<List<String>> accounts) {
parent = new int[accounts.size()];
size = accounts.size();
// Arrays.fill(parent, -1);
for (int i = 0; i < accounts.size(); i++) {
parent[i] = i;
for (String email : accounts.get(i)) {
}
}
}

public int findRoot(int node) {
if (isRoot(node)) {
return node;
}

int root = findRoot(parent[node]);
parent[node] = root;
return root;
}

public void union(Set<Integer> roots, int newRoot) {
// roots = findNotMergedRoot(roots);
for (int root : roots) {
// parent[root] = newRoot; // WRONG
parent[findRoot(parent[root])] = newRoot;
// size--;
}
}

public Set<Integer> getGroup(List<String> emails) {
Set<Integer> groups = new HashSet<>();
for (String email : emails) {
if (emailGroups.containsKey(email)) {
// emailGroups.put(email, findRootNodes(emailGroups.get(email)));
}
}
return groups;
}

private Set<Integer> findRootNodes(Set<Integer> roots) {
return roots.stream().filter(i -> isRoot(i)).collect(Collectors.toSet());
}

private boolean isRoot(Integer i) {
return parent[i] == i;
}

@Override
public String toString() {
return "UnionFind [parent=" + Arrays.toString(parent) + ", emailGroups=" + emailGroups + ", size=" + size
+ "]";
}
}

Draw an edge between two emails if they occur in the same account. The problem comes down to finding connected components of this graph.
Algorithm
For each account, draw the edge from the first email to all other emails. Additionally, we'll remember a map from emails to names on the side. After finding each connected component using a depth-first search, we'll add that to our answer.
• Time Complexity: $O(\sum a_i \log a_i)$, where $a_i$ is the length of accounts[i]. Without the log factor, this is the complexity to build the graph and search for each component. The log factor is for sorting each component at the end.
• Space Complexity: $O(\sum a_i)$, the space used by our graph and our search.
    public List<List<String>> accountsMerge(List<List<String>> accounts) {
Map<String, String> emailToName = new HashMap();
Map<String, ArrayList<String>> graph = new HashMap();
for (List<String> account: accounts) {
String name = "";
for (String email: account) {
if (name == "") {
name = email;
continue;
}
emailToName.put(email, name);
}
}

Set<String> seen = new HashSet();
List<List<String>> ans = new ArrayList();
for (String email: graph.keySet()) {
if (!seen.contains(email)) {
Stack<String> stack = new Stack();
stack.push(email);
List<String> component = new ArrayList();
while (!stack.empty()) {
String node = stack.pop();
for (String nei: graph.get(node)) {
if (!seen.contains(nei)) {
stack.push(nei);
}
}
}
Collections.sort(component);
}
}
return ans;
}