Restore the Array From Adjacent Pairs - Problem
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.
Input & Output
Example 1 — Basic Linear Chain
$
Input:
adjacentPairs = [[2,1],[1,3]]
›
Output:
[2,1,3]
💡 Note:
The pairs tell us 2 connects to 1, and 1 connects to 3. Since 2 and 3 each have only one neighbor, they are endpoints. Starting from endpoint 2: 2→1→3.
Example 2 — Longer Chain
$
Input:
adjacentPairs = [[4,2],[1,4],[3,1]]
›
Output:
[2,4,1,3]
💡 Note:
Build graph: 4↔2, 4↔1, 1↔3. Endpoints are 2 and 3 (one neighbor each). Starting from 2: 2→4→1→3.
Example 3 — Two Elements
$
Input:
adjacentPairs = [[100,200]]
›
Output:
[100,200]
💡 Note:
Minimum case: only one pair means two adjacent elements. Both are endpoints, so either [100,200] or [200,100] is valid.
Constraints
- nums.length == n
- adjacentPairs.length == n - 1
- 2 ≤ n ≤ 105
- -105 ≤ nums[i], ui, vi ≤ 105
- There exists some nums that has adjacentPairs as its pairs
Visualization
Tap to expand
Understanding the Visualization
1
Input
Adjacent pairs: [[2,1],[1,3]]
2
Process
Build graph: 2↔1↔3, find endpoints
3
Output
Restored array: [2,1,3]
Key Takeaway
🎯 Key Insight: The array forms a linear chain - find an endpoint and traverse to reconstruct the sequence
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code