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 <= 105nums that has adjacentPairs as its pairs.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a puzzle of connected pairs of items that have been jumbled up, and you need to line them all up in a single correct sequence. The brute force approach involves blindly guessing every single possible ordering of the items from start to finish.
Here's how the algorithm would work step-by-step:
import itertools
def restore_array(adjacent_pairs):
unique_elements = set()
for pair in adjacent_pairs:
unique_elements.add(pair[0])
unique_elements.add(pair[1])
# We generate all possible permutations because the brute force strategy requires checking every ordering
for trial_sequence in itertools.permutations(unique_elements):
is_valid_sequence = True
for index in range(len(trial_sequence) - 1):
current_pair = {trial_sequence[index], trial_sequence[index + 1]}
found_match = False
for original_pair in adjacent_pairs:
if set(original_pair) == current_pair:
found_match = True
break
if not found_match:
is_valid_sequence = False
break
# We return the first sequence that satisfies all adjacent pair rules to solve the puzzle
if is_valid_sequence:
return list(trial_sequence)
return []Imagine you have a puzzle where every piece tells you which two pieces must sit right next to each other, but the pieces are completely jumbled up. The best way to solve this is to first figure out where the line of pieces must start and end by finding the unique pieces that only have a single neighbor, and then simply walk down the line from one end to the other.
Here's how the algorithm would work step-by-step:
from collections import defaultdict
def restore_array(adjacent_pairs):
adjacency_map = defaultdict(list)
for element_u, element_v in adjacent_pairs:
adjacency_map[element_u].append(element_v)
adjacency_map[element_v].append(element_u)
# We identify endpoints because boundary elements only have one neighbor.
start_element = None
for candidate_key, neighbors in adjacency_map.items():
if len(neighbors) == 1:
start_element = candidate_key
break
restored_array = [start_element]
current_element = start_element
previous_element = None
# We traverse the chain until we reach the other single-neighbor boundary.
while len(restored_array) < len(adjacency_map):
next_candidates = adjacency_map[current_element]
for neighbor in next_candidates:
if neighbor != previous_element:
previous_element = current_element
current_element = neighbor
restored_array.append(current_element)
break
# The reconstructed sequence is returned once all adjacent pairs are walked.
return restored_array| Case | How to Handle |
|---|---|
| Minimum valid input with a single adjacent pair | The graph traversal correctly identifies both elements as endpoints with a degree of one and returns them in either valid order. |
| Negative numbers and zero values present in the input pairs | Using a hash map for adjacency list construction naturally accommodates any integer value as a key without requiring coordinate offsets. |
| Large scale input approaching maximum constraints | An adjacency map and linear traversal ensure time and space complexity remain proportional to the number of elements, preventing memory or timeout limits. |
| Reconstruction direction ambiguity | The problem statement explicitly allows returning the array in either forward or reverse order, so either valid endpoint can serve as the starting node. |
| Deep recursion during graph traversal | Using an iterative loop instead of recursive DFS avoids stack overflow exceptions when traversing the long linear sequence. |
| Elements with a degree of two versus endpoints with a degree of one | Scanning the adjacency map for a node with exactly one neighbor allows us to reliably pinpoint the start of the sequence. |
| Duplicate values allowed across different positions in the hidden array | The problem guarantees every element appears at most twice, which prevents complex branching and guarantees a strictly linear graph structure. |