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
Restore Array From Adjacent Pairs Hash Map - Build Adjacency Graph Approach INPUT adjacentPairs array: [2, 1] pair 0 [1, 3] pair 1 Graph Visualization: 2 1 3 Nodes connected by edges from adjacent pairs n = 3 elements ALGORITHM STEPS 1 Build Adjacency Map Store neighbors for each num map[2] = [1] map[1] = [2, 3] map[3] = [1] degree: 1, 2, 1 2 Find Start Element Node with degree 1 (endpoint) Start = 2 (or 3) 3 Traverse Graph Walk through neighbors 2 --> 1 --> 3 Track visited to avoid backtrack 4 Build Result Array Collect elements in order O(n) time, O(n) space FINAL RESULT Restored Original Array: 2 idx 0 1 idx 1 3 idx 2 Output: [2, 1, 3] Verification: Adjacent pairs check: [2,1] in pairs? OK [1,3] in pairs? OK All pairs matched! [3,1,2] also valid Key Insight: The adjacent pairs form a path graph where endpoints have exactly ONE neighbor (degree 1). Start from any endpoint and traverse using the adjacency map, skipping visited nodes. This reconstructs the original array in O(n) time using a hash map for O(1) neighbor lookups. TutorialsPoint - Restore the Array From Adjacent Pairs | Hash Map Adjacency Graph Approach
Asked in
Facebook 15 Google 12 Amazon 8
68.0K Views
Medium Frequency
~15 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen