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.47 KB
/
Accounts Merge.java
File metadata and controls
38 lines (38 loc) · 1.47 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, List<String>> adjacencyList = new HashMap<>();
for (List<String> account : accounts) {
String firstEmail = account.get(1);
for (int i = 2; i < account.size(); i++) {
adjacencyList.computeIfAbsent(firstEmail, k -> new ArrayList<>()).add(account.get(i));
adjacencyList.computeIfAbsent(account.get(i), k -> new ArrayList<>()).add(firstEmail);
}
}
Set<String> visited = new HashSet<>();
List<List<String>> mergedAccounts = new ArrayList<>();
for (List<String> account : accounts) {
String name = account.get(0);
String firstEmail = account.get(1);
if (!visited.contains(firstEmail)) {
Stack<String> stack = new Stack<>();
stack.push(firstEmail);
List<String> mergedAccount = new ArrayList<>();
mergedAccount.add(name);
while (!stack.isEmpty()) {
String removedEmail = stack.pop();
visited.add(removedEmail);
mergedAccount.add(removedEmail);
for (String neighbor : adjacencyList.getOrDefault(removedEmail, new ArrayList<>())) {
if (!visited.contains(neighbor)) {
visited.add(neighbor);
stack.push(neighbor);
}
}
}
Collections.sort(mergedAccount.subList(1, mergedAccount.size()));
mergedAccounts.add(mergedAccount);
}
}
return mergedAccounts;
}
}