-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValid Arrangement of Pairs
46 lines (39 loc) · 1.67 KB
/
Valid Arrangement of Pairs
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
39
40
41
42
43
44
45
46
class Solution {
public int[][] validArrangement(int[][] pairs) {
Map<Integer, List<Integer>> adjacencyList = new HashMap<>();
Map<Integer, Integer> inOutDegree = new HashMap<>();
// Build graph and count in/out degrees
for (int[] pair : pairs) {
adjacencyList.computeIfAbsent(pair[0], k -> new ArrayList<>()).add(pair[1]);
inOutDegree.merge(pair[0], 1, Integer::sum); // out-degree
inOutDegree.merge(pair[1], -1, Integer::sum); // in-degree
}
// Find starting node
int startNode = pairs[0][0];
for (Map.Entry<Integer, Integer> entry : inOutDegree.entrySet()) {
if (entry.getValue() == 1) {
startNode = entry.getKey();
break;
}
}
List<Integer> path = new ArrayList<>();
Deque<Integer> nodeStack = new ArrayDeque<>();
nodeStack.push(startNode);
while (!nodeStack.isEmpty()) {
List<Integer> neighbors = adjacencyList.getOrDefault(nodeStack.peek(), new ArrayList<>());
if (neighbors.isEmpty()) {
path.add(nodeStack.pop());
} else {
int nextNode = neighbors.get(neighbors.size() - 1);
nodeStack.push(nextNode);
neighbors.remove(neighbors.size() - 1);
}
}
int pathSize = path.size();
int[][] arrangement = new int[pathSize - 1][2];
for (int i = pathSize - 1; i > 0; --i) {
arrangement[pathSize - 1 - i] = new int[]{path.get(i), path.get(i-1)};
}
return arrangement;
}
}