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 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.
There exists some nums that has adjacentPairs as its pairs.
Solution:
We can create an adjacency list by iterating over all adjacentPairs. This represents a graph with structure like an array ie two nodes (left and right ends) have one neighbor whereas the rest have two neighbors each.
We can run DFS from one of the terminal nodes to get all nodes of graph in the order in which they appear in the original array.
SOLUTION II:
Since we already know the graph structure, we can also do the traversal in the following way:
We find out the start and end nodes. We initialize cur with start and iterate till cur is same as end.