[LeetCode] Restore the Array From Adjacent Pairs

1743. Restore the Array From Adjacent Pairs

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
void dfs(unordered_map<int, vector<int>>& adj, int u, vector<int>& res, int par = INT_MIN) {
res.push_back(u);
for(auto& v : adj[u]) {
if(v == par) continue;
dfs(adj, v, res, u);
}
}
public:
vector<int> restoreArray(vector<vector<int>>& A) {
unordered_map<int, vector<int>> adj;
for(auto& a : A) {
int u = a[0], v = a[1];
adj[u].push_back(v);
adj[v].push_back(u);
}
vector<int> res;

for(auto& [u, vs] : adj) {
if(vs.size() == 1) {
dfs(adj, u, res);
return res;
}
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/02/PS/LeetCode/restore-the-array-from-adjacent-pairs/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.