Skip to content

1743. Restore the Array From Adjacent Pairs

Description

There is an integer array nums that consists of n unique elements, but you have forgotten it. However, you do remember every pair of adjacent elements in nums.

You are given a 2D integer array adjacentPairs of size n - 1 where each adjacentPairs[i] = [ui, vi] indicates that the elements ui and vi are adjacent in nums.

It is guaranteed that every adjacent pair of elements nums[i] and nums[i+1] will exist in adjacentPairs, either as [nums[i], nums[i+1]] or [nums[i+1], nums[i]]. The pairs can appear in any order.

Return the original array nums. If there are multiple solutions, return any of them.

 

Example 1:

Input: adjacentPairs = [[2,1],[3,4],[3,2]]
Output: [1,2,3,4]
Explanation: This array has all its adjacent pairs in adjacentPairs.
Notice that adjacentPairs[i] may not be in left-to-right order.

Example 2:

Input: adjacentPairs = [[4,-2],[1,4],[-3,1]]
Output: [-2,4,1,-3]
Explanation: There can be negative numbers.
Another solution is [-3,1,4,-2], which would also be accepted.

Example 3:

Input: adjacentPairs = [[100000,-100000]]
Output: [100000,-100000]

 

Constraints:

  • nums.length == n
  • adjacentPairs.length == n - 1
  • adjacentPairs[i].length == 2
  • 2 <= n <= 105
  • -105 <= nums[i], ui, vi <= 105
  • There exists some nums that has adjacentPairs as its pairs.

 

Solutions

Solution: Hash Map

  • Time complexity: O(n*2)
  • Space complexity: O(n*2)

 

JavaScript

js
/**
 * @param {number[][]} adjacentPairs
 * @return {number[]}
 */
const restoreArray = function (adjacentPairs) {
  const pairsMap = adjacentPairs.reduce((map, [a, b]) => {
    const pairsA = map.get(a) ?? new Set();
    const pairsB = map.get(b) ?? new Set();

    map.set(a, pairsA.add(b));
    return map.set(b, pairsB.add(a));
  }, new Map());
  const size = adjacentPairs.length + 1;
  const startNum = [...pairsMap.keys()].find(num => pairsMap.get(num).size === 1);
  const result = [startNum];

  for (let index = 1; index < size; index++) {
    const current = result[index - 1];
    const pairs = pairsMap.get(current);

    for (const num of pairs) {
      if (num === result[index - 2]) continue;
      result.push(num);
    }
  }
  return result;
};

Released under the MIT license