-
-
Notifications
You must be signed in to change notification settings - Fork 8k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
38a4c67
commit 5bbe9e0
Showing
1 changed file
with
47 additions
and
0 deletions.
There are no files selected for viewing
47 changes: 47 additions & 0 deletions
47
solution/2000-2099/2097.Valid Arrangement of Pairs/Solution.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
/** | ||
* @param {number[][]} pairs | ||
* @return {number[][]} | ||
*/ | ||
var validArrangement = function(pairs) { | ||
const graph = new Map(); | ||
const indegree = new Map(); | ||
const outdegree = new Map(); | ||
|
||
for (const [start, end] of pairs) { | ||
if (!graph.has(start)) graph.set(start, []); | ||
graph.get(start).push(end); | ||
|
||
outdegree.set(start, (outdegree.get(start) || 0) + 1); | ||
indegree.set(end, (indegree.get(end) || 0) + 1); | ||
} | ||
|
||
let startNode = pairs[0][0]; | ||
for (const [node, out] of outdegree) { | ||
const inCount = indegree.get(node) || 0; | ||
if (out - inCount === 1) { | ||
startNode = node; | ||
break; | ||
} | ||
} | ||
|
||
const result = []; | ||
const stack = [startNode]; | ||
|
||
while (stack.length) { | ||
const node = stack[stack.length - 1]; | ||
if (graph.has(node) && graph.get(node).length > 0) { | ||
stack.push(graph.get(node).pop()); | ||
} else { | ||
result.push(stack.pop()); | ||
} | ||
} | ||
|
||
result.reverse(); | ||
|
||
const output = []; | ||
for (let i = 1; i < result.length; i++) { | ||
output.push([result[i - 1], result[i]]); | ||
} | ||
|
||
return output; | ||
}; |