|
| 1 | +/** |
| 2 | + * 1743. Restore the Array From Adjacent Pairs |
| 3 | + * https://leetcode.com/problems/restore-the-array-from-adjacent-pairs/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * There is an integer array nums that consists of n unique elements, but you have |
| 7 | + * forgotten it. However, you do remember every pair of adjacent elements in nums. |
| 8 | + * |
| 9 | + * You are given a 2D integer array adjacentPairs of size n - 1 where each |
| 10 | + * adjacentPairs[i] = [ui, vi] indicates that the elements ui and vi are adjacent in nums. |
| 11 | + * |
| 12 | + * It is guaranteed that every adjacent pair of elements nums[i] and nums[i+1] will exist in |
| 13 | + * adjacentPairs, either as [nums[i], nums[i+1]] or [nums[i+1], nums[i]]. The pairs can appear |
| 14 | + * in any order. |
| 15 | + * |
| 16 | + * Return the original array nums. If there are multiple solutions, return any of them. |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * @param {number[][]} adjacentPairs |
| 21 | + * @return {number[]} |
| 22 | + */ |
| 23 | +var restoreArray = function(adjacentPairs) { |
| 24 | + const graph = new Map(); |
| 25 | + for (const [u, v] of adjacentPairs) { |
| 26 | + graph.set(u, (graph.get(u) || []).concat(v)); |
| 27 | + graph.set(v, (graph.get(v) || []).concat(u)); |
| 28 | + } |
| 29 | + |
| 30 | + let start; |
| 31 | + for (const [node, neighbors] of graph) { |
| 32 | + if (neighbors.length === 1) { |
| 33 | + start = node; |
| 34 | + break; |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + const result = [start]; |
| 39 | + let prev = start; |
| 40 | + let curr = graph.get(start)[0]; |
| 41 | + |
| 42 | + while (graph.get(curr).length > 1) { |
| 43 | + result.push(curr); |
| 44 | + const next = graph.get(curr).find(n => n !== prev); |
| 45 | + prev = curr; |
| 46 | + curr = next; |
| 47 | + } |
| 48 | + result.push(curr); |
| 49 | + |
| 50 | + return result; |
| 51 | +}; |
0 commit comments