forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAccounts Merge.java
More file actions
38 lines (38 loc) · 1.32 KB
/
Accounts Merge.java
File metadata and controls
38 lines (38 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
public List<List<String>> accountsMerge(List<List<String>> accounts) {
Map<String, String> emailToNameMap = new HashMap<>();
Map<String, Set<String>> graph = new HashMap<>();
for (List<String> account : accounts) {
String name = account.get(0);
for (int i = 1; i < account.size(); i++) {
emailToNameMap.put(account.get(i), name);
graph.computeIfAbsent(account.get(i), k -> new HashSet<>()).add(account.get(1));
graph.computeIfAbsent(account.get(1), k -> new HashSet<>()).add(account.get(i));
}
}
Set<String> seen = new HashSet<>();
List<List<String>> ans = new ArrayList<>();
for (String email : graph.keySet()) {
if (!seen.contains(email)) {
seen.add(email);
Stack<String> stack = new Stack<>();
stack.push(email);
List<String> component = new ArrayList<>();
while (!stack.isEmpty()) {
String node = stack.pop();
component.add(node);
for (String neighbour : graph.get(node)) {
if (!seen.contains(neighbour)) {
seen.add(neighbour);
stack.push(neighbour);
}
}
}
Collections.sort(component);
component.add(0, emailToNameMap.get(email));
ans.add(component);
}
}
return ans;
}
}