Skip to content

Commit 5bbe9e0

Browse files
authored
Create Solution.js
1 parent 38a4c67 commit 5bbe9e0

File tree

1 file changed

+47
-0
lines changed
  • solution/2000-2099/2097.Valid Arrangement of Pairs

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* @param {number[][]} pairs
3+
* @return {number[][]}
4+
*/
5+
var validArrangement = function(pairs) {
6+
const graph = new Map();
7+
const indegree = new Map();
8+
const outdegree = new Map();
9+
10+
for (const [start, end] of pairs) {
11+
if (!graph.has(start)) graph.set(start, []);
12+
graph.get(start).push(end);
13+
14+
outdegree.set(start, (outdegree.get(start) || 0) + 1);
15+
indegree.set(end, (indegree.get(end) || 0) + 1);
16+
}
17+
18+
let startNode = pairs[0][0];
19+
for (const [node, out] of outdegree) {
20+
const inCount = indegree.get(node) || 0;
21+
if (out - inCount === 1) {
22+
startNode = node;
23+
break;
24+
}
25+
}
26+
27+
const result = [];
28+
const stack = [startNode];
29+
30+
while (stack.length) {
31+
const node = stack[stack.length - 1];
32+
if (graph.has(node) && graph.get(node).length > 0) {
33+
stack.push(graph.get(node).pop());
34+
} else {
35+
result.push(stack.pop());
36+
}
37+
}
38+
39+
result.reverse();
40+
41+
const output = [];
42+
for (let i = 1; i < result.length; i++) {
43+
output.push([result[i - 1], result[i]]);
44+
}
45+
46+
return output;
47+
};

0 commit comments

Comments
 (0)