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] = [u_i, v_i]
indicates that the elements u_i
and v_i
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. Here are some examples:
adjacentPairs = [[2,1],[3,4],[3,2]]
. The output should be [1,2,3,4]
.adjacentPairs = [[4,-2],[1,4],[-3,1]]
. The output should be [-2,4,1,-3]
.adjacentPairs = [[100000,-100000]]
. The output should be [100000,-100000]
.Can you write an algorithm for this problem?
def restore_array(adjacentPairs):
"""
Given an array of adjacent pairs, reconstruct the original array.
Args:
adjacentPairs (List[List[int]]): A list of adjacent pairs.
Returns:
List[int]: The reconstructed array.
"""
graph = {}
degrees = {}
for u, v in adjacentPairs:
graph.setdefault(u, []).append(v)
graph.setdefault(v, []).append(u)
degrees[u] = degrees.get(u, 0) + 1
degrees[v] = degrees.get(v, 0) + 1
start_node = None
for node, degree in degrees.items():
if degree == 1:
start_node = node
break
result = []
visited = {start_node}
def dfs(node):
result.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
dfs(neighbor)
dfs(start_node)
return result
# Example Usage:
# adjacentPairs = [[2,1],[3,4],[3,2]]
# print(restore_array(adjacentPairs)) # Output: [1, 2, 3, 4] or equivalent
# adjacentPairs = [[4,-2],[1,4],[-3,1]]
# print(restore_array(adjacentPairs)) # Output: [-2, 4, 1, -3] or equivalent
# adjacentPairs = [[100000,-100000]]
# print(restore_array(adjacentPairs)) # Output: [100000, -100000]
Build the Graph:
nums
, and values are lists of their adjacent numbers.degrees
dictionary to store the degree of each node, representing the number of adjacent nodes it has.Find the Start Node:
Depth-First Search (DFS):
start_node
.result
list.Return the Result:
result
list now contains the reconstructed array.adjacentPairs
once to build the graph, and then we perform a DFS that visits each node once.adjacentPairs
is empty, return an empty array.adjacentPairs
contains only one pair, return the array containing that pair's elements.nums
that has adjacentPairs
as its pairs. Therefore, it is guaranteed to be a connected graph and we don't need to handle disconnected components. If the question were to NOT provide such a guarantee, we would need to loop through each discovered disconnected component and perform DFS on each to recover the full array.