From 5bbe9e0edef2824282c78a2754bb193f5eeae868 Mon Sep 17 00:00:00 2001 From: Subhadip Hensh <91666506+07subhadip@users.noreply.github.com> Date: Sat, 30 Nov 2024 09:24:23 +0530 Subject: [PATCH] Create Solution.js --- .../Solution.js | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 solution/2000-2099/2097.Valid Arrangement of Pairs/Solution.js diff --git a/solution/2000-2099/2097.Valid Arrangement of Pairs/Solution.js b/solution/2000-2099/2097.Valid Arrangement of Pairs/Solution.js new file mode 100644 index 0000000000000..685b12bc11ae3 --- /dev/null +++ b/solution/2000-2099/2097.Valid Arrangement of Pairs/Solution.js @@ -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; +};