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 == nadjacentPairs.length == n - 1adjacentPairs[i].length == 22 <= n <= 105-105 <= nums[i], ui, vi <= 105- There exists some
numsthat hasadjacentPairsas its pairs.
Companies: Uber, Capital One, Microsoft, Robinhood
Related Topics:
Array, Hash Table
Hints:
- Find the first element of nums - it will only appear once in adjacentPairs.
- The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
// OJ: https://leetcode.com/problems/restore-the-array-from-adjacent-pairs
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
public:
vector<int> restoreArray(vector<vector<int>>& A) {
int N = A.size() + 1, first = -1;
unordered_map<int, vector<int>> G;
for (auto &p : A) { // build graph
int u = p[0], v = p[1];
G[u].push_back(v);
G[v].push_back(u);
}
vector<int> ans;
for (auto &[n, v] : G) { // find an edge node
if (v.size() == 1) {
ans.push_back(n);
ans.push_back(v[0]);
break;
}
}
while (ans.size() < N) { // keep finding the next node
int n = ans.back(), prev = ans[ans.size() - 2];
if (G[n][0] != prev) ans.push_back(G[n][0]);
else ans.push_back(G[n][1]);
}
return ans;
}
};