There is an integer array nums that consists of nunique 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 arraynums. If there are multiple solutions, return any of them.
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:
1
2
3
4
5
6
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.
Each number in the array is adjacent to at most two other numbers, except for the endpoints, which are adjacent to only one. By building a graph from the pairs, we can start from an endpoint and reconstruct the array by traversing through the neighbors.
classSolution:
defrestoreArray(self, adjacentPairs: list[list[int]]) -> list[int]:
from collections import defaultdict
graph = defaultdict(list)
for u, v in adjacentPairs:
graph[u].append(v)
graph[v].append(u)
# Find endpointfor k, v in graph.items():
if len(v) ==1:
start = k
break ans = [start]
prev =Nonewhile len(ans) < len(graph):
curr = ans[-1]
for nei in graph[curr]:
if nei != prev:
ans.append(nei)
prev = curr
breakreturn ans