Talentd
FleetCode
Make and follow sheets.Sign in

Restore the Array From Adjacent Pairs solution and explanation

MediumArrayDepth-First SearchHash Table6 min read74.7% acceptanceUpdated 9 Apr 2026
Restore the Array From Adjacent Pairs | Easy Explanation | Dry Run | Intuition | Leetcode-1743codestorywithMIK · 20:31 · 7K viewsWatch on YouTube
9 more videos on this problem
  1. Restore the Array From Adjacent Pairs | Easy Explanation | Dry Run | Intuition | Leetcode-1743codestorywithMIK · 20:31 · 7K views
  2. Leetcode 1743. Restore the Array From Adjacent PairsFraz · 9:57 · 6K views
  3. 1743. Restore the Array From Adjacent Pairs | 3 waysAryan Mittal · 17:42 · 2K views
  4. LeetCode 1743. Restore the Array From Adjacent PairsHappy Coding · 12:20 · 2K views
  5. LeetCode 1743. Restore the Array From Adjacent Pairs | Visualization | PythonAH Tech · 7:32 · 1K views
  6. Leetcode Solution - 1743 Restore the Array From Adjacent PairsJohn Leonardo · 7:32 · 913 views
  7. 1743. Restore the Array From Adjacent Pairs (Leetcode Medium)Programming Live with Larry · 9:29 · 544 views
  8. Restore the Array From Adjacent Pairs | Решение на Python | LeetCode 1743Сурен Хоренян · 11:13 · 354 views
  9. Daily Leetcode #1319: Nov 10, 2023 - 1743. Restore the Array From Adjacent PairsProgramming Live with Larry · 11:03 · 300 views
  10. Solving LeetCode 1743 Restore the Array From Adjacent Pairs | HashTable | Easy to UnderstandCode Harmony · 15:21 · 204 views

The 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.

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 == n
  • adjacentPairs.length == n - 1
  • adjacentPairs[i].length == 2
  • 2 <= n <= 105
  • -105 <= nums[i], ui, vi <= 105
  • There exists some nums that has adjacentPairs as its pairs.

Approach overview

Problem Overview: You receive adjacentPairs, where each pair represents two neighboring elements in an unknown array. The task is to reconstruct the original array. Every element appears in at most two pairs, which means the structure naturally forms a linear chain when modeled as a graph.

Approach 1: Graph Construction and Traversal (O(n) time, O(n) space)

Treat each number as a node and each adjacent pair as an undirected edge. Build an adjacency list using a hash table where each value maps to its neighbors. In the reconstructed array, the two endpoints appear only once in the pairs, so their adjacency list has size 1. Start from any endpoint, then repeatedly move to the neighbor that has not been visited yet.

This becomes a simple path traversal problem on a graph with maximum degree 2. Maintain a visited set or track the previous element to avoid going backward. You can implement the traversal iteratively or with depth-first search. Since every element is processed once, the algorithm runs in O(n) time with O(n) space for the adjacency structure.

This approach works because the graph is guaranteed to form a single chain rather than multiple branches. Endpoints anchor the reconstruction, and each step reveals the next element in the sequence.

Approach 2: Graph Construction and Ordering with Sorting (O(n log n) time, O(n) space)

Another option is to first construct the same adjacency list, then order elements based on traversal rules while maintaining a structure that determines the next node deterministically. Some implementations sort adjacency lists so the traversal always chooses neighbors in a consistent order.

After identifying an endpoint (degree 1 node), iterate through neighbors and append them to the result array while marking visited elements. Sorting adds overhead but simplifies deterministic ordering logic in some languages such as C#. The reconstruction still follows the single-chain property of the graph.

This version has O(n log n) time complexity due to sorting operations and O(n) extra space for the graph and visited tracking.

Recommended for interviews: The graph construction and traversal approach is what interviewers expect. Modeling the problem as a path in a graph shows strong understanding of array relationships and adjacency structures. Identifying endpoints and performing a linear traversal achieves the optimal O(n) time complexity, which demonstrates algorithmic efficiency.

Approach 1: Graph Construction and Traversal

In this approach, we will treat the problem as one of finding a path in a graph. Each element in the array is a node, and each adjacent pair represents an edge connecting two nodes. We can represent this graph using an adjacency list.

First, build the adjacency list from the given pairs. Elements with degree 1 (i.e., nodes with only one neighbor) are potential starting or ending points for the original array. We pick one such node and perform a depth-first search (DFS) or breadth-first search (BFS) to reconstruct the array.

from collections import defaultdict

def restoreArray(adjacentPairs):
    adj_map = defaultdict(list)
    for u, v in adjacentPairs:
        adj_map[u].append(v)
        adj_map[v].append(u)

    # Find a starting point (it should have a single connection)
    start = next(k for k, v in adj_map.items() if len(v) == 1)

    # Restore the array by traversing
    res = []
    visited = set()
    current = start
    prev = None
    while current is not None:
        res.append(current)
        visited.add(current)
        neighbors = adj_map[current]
        next_node = next((n for n in neighbors if n != prev), None)
        prev = current
        current = next_node

    return res
import java.util.*;

public class Solution {
    public int[] restoreArray(int[][] adjacentPairs) {
        Map<Integer, List<Integer>> adjMap = new HashMap<>();

        // Construct the adjacency map
        for (int[] pair : adjacentPairs) {
            adjMap.putIfAbsent(pair[0], new ArrayList<>());
            adjMap.putIfAbsent(pair[1], new ArrayList<>());
            adjMap.get(pair[0]).add(pair[1]);
            adjMap.get(pair[1]).add(pair[0]);
        }

        // Find the starting point
        int start = 0;
        for (Map.Entry<Integer, List<Integer>> entry : adjMap.entrySet()) {
            if (entry.getValue().size() == 1) {
                start = entry.getKey();
                break;
            }
        }

        // Reconstruct the original array
        int[] result = new int[adjMap.size()];
        Set<Integer> visited = new HashSet<>();
        result[0] = start;
        visited.add(start);
        int prev = -1;
        for (int i = 1; i < result.length; i++) {
            List<Integer> neighbors = adjMap.get(start);
            for (int neighbor : neighbors) {
                if (!visited.contains(neighbor)) {
                    result[i] = neighbor;
                    visited.add(neighbor);
                    prev = start;
                    start = neighbor;
                    break;
                }
            }
        }

        return result;
    }
}
#include <vector>
#include <unordered_map>
#include <unordered_set>

using namespace std;

vector<int> restoreArray(vector<vector<int>>& adjacentPairs) {
    unordered_map<int, vector<int>> adjMap;
    for (const auto& pair : adjacentPairs) {
        adjMap[pair[0]].push_back(pair[1]);
        adjMap[pair[1]].push_back(pair[0]);
    }

    int start = 0;
    for (const auto& [key, neighbors] : adjMap) {
        if (neighbors.size() == 1) {
            start = key;
            break;
        }
    }

    vector<int> result;
    unordered_set<int> visited;
    int prev = -1;

    while (true) {
        result.push_back(start);
        visited.insert(start);
        auto& neighbors = adjMap[start];
        int next = -1;
        for (const auto& neighbor : neighbors) {
            if (neighbor != prev && visited.find(neighbor) == visited.end()) {
                next = neighbor;
                break;
            }
        }
        if (next == -1) break;
        prev = start;
        start = next;
    }

    return result;
}
function restoreArray(adjacentPairs) {
    const adjMap = new Map();

    // Construct the adjacency map
    for (const [u, v] of adjacentPairs) {
        if (!adjMap.has(u)) adjMap.set(u, []);
        if (!adjMap.has(v)) adjMap.set(v, []);
        adjMap.get(u).push(v);
        adjMap.get(v).push(u);
    }

    // Find the starting point
    let start;
    for (const [key, neighbors] of adjMap.entries()) {
        if (neighbors.length === 1) {
            start = key;
            break;
        }
    }

    // Reconstruct the original array
    const result = [];
    const visited = new Set();
    let prev = null;
    let current = start;

    while (current !== undefined) {
        result.push(current);
        visited.add(current);
        const neighbors = adjMap.get(current);
        const next = neighbors.find(n => n !== prev);
        prev = current;
        current = visited.has(next) ? undefined : next;
    }

    return result;
}

This Python solution constructs an adjacency list using defaultdict from the collections module. It picks a starting node with a single connection, then performs a traversal using a while loop to reconstruct the array. Nodes are marked as visited to avoid revisiting.

Complexity

Time Complexity: O(n), where n is the number of elements in nums.
Space Complexity: O(n), for storing the adjacency list and visited set.

Try this approach in the editor

Approach 2: Graph Construction and Sorting

This approach builds the adjacency list similar to the previous one but uses sorting to aid in selecting the next node. While sorting might not always be the primary mechanism to solve the problem, it ensures adjacent nodes can be identified quickly, which helps in managing which node to process next in the construction of the resultant array.

using System;
using System.Collections.Generic;

public class Solution {
    public int[] RestoreArray(int[][] adjacentPairs) {
        var adjMap = new Dictionary<int, List<int>>();

        // Build the adjacency map
        foreach (var pair in adjacentPairs) {
            if (!adjMap.ContainsKey(pair[0])) adjMap[pair[0]] = new List<int>();
            if (!adjMap.ContainsKey(pair[1])) adjMap[pair[1]] = new List<int>();
            adjMap[pair[0]].Add(pair[1]);
            adjMap[pair[1]].Add(pair[0]);
        }

        // Find the start of the array
        int start = 0;
        foreach (var kvp in adjMap) {
            if (kvp.Value.Count == 1) {
                start = kvp.Key;
                break;
            }
        }

        // Reconstruct the array
        List<int> result = new List<int>();
        HashSet<int> visited = new HashSet<int>();
        int prev = -1;

        while (true) {
            result.Add(start);
            visited.Add(start);
            var neighbors = adjMap[start];
            int next = -1;
            foreach (var neighbor in neighbors) {
                if (neighbor != prev && !visited.Contains(neighbor)) {
                    next = neighbor;
                    break;
                }
            }
            if (next == -1) break;
            prev = start;
            start = next;
        }

        return result.ToArray();
    }
}

The C# solution is similar in spirit to the earlier ones. It builds a dictionary for adjacency mapping and rebuilds the array by picking nodes not yet visited. It emphasizes cleanliness and direct approach instead of relying on complex loops or conditional checks.

Complexity

Time Complexity: O(n). Space Complexity: O(n), for maintaining necessary data structures.

Try this approach in the editor

Approach 3: Default Approach

func restoreArray(adjacentPairs [][]int) []int {
	n := len(adjacentPairs) + 1
	g := map[int][]int{}
	for _, e := range adjacentPairs {
		a, b := e[0], e[1]
		g[a] = append(g[a], b)
		g[b] = append(g[b], a)
	}
	ans := make([]int, n)
	for k, v := range g {
		if len(v) == 1 {
			ans[0] = k
			ans[1] = v[0]
			break
		}
	}
	for i := 2; i < n; i++ {
		v := g[ans[i-1]]
		ans[i] = v[0]
		if v[0] == ans[i-2] {
			ans[i] = v[1]
		}
	}
	return ans
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Graph Construction and Traversal

Time Complexity: O(n), where n is the number of elements in nums.
Space Complexity: O(n), for storing the adjacency list and visited set.

Graph Construction and Sorting

Time Complexity: O(n). Space Complexity: O(n), for maintaining necessary data structures.

Default Approach–

Complexity analysis

ApproachTimeSpaceWhen to Use
Graph Construction and TraversalO(n)O(n)Best general solution. Linear traversal from endpoint using adjacency list.
Graph Construction with SortingO(n log n)O(n)Useful when deterministic neighbor ordering is needed or when implementation favors sorted adjacency lists.

Frequently asked questions

Is Restore the Array From Adjacent Pairs easy or hard?

Restore the Array From Adjacent Pairs is classified as a Medium problem. The main challenge is recognizing that the pairs form a path-like graph and that endpoints have only one neighbor. Once modeled as a graph traversal problem, the implementation becomes straightforward.

Restore the Array From Adjacent Pairs Python/Java solution

The standard implementation builds an adjacency list using a dictionary or HashMap, finds a starting endpoint, and performs a linear traversal while tracking the previous element. This approach works in Python, Java, C++, and JavaScript with O(n) time complexity.

How to solve Restore the Array From Adjacent Pairs in O(n)?

Create an adjacency list with a hash map mapping each value to its neighbors. Identify a starting element with only one neighbor, which represents an endpoint of the original array. Then iteratively append the next neighbor that is not equal to the previous element. Since every element is visited once, the algorithm runs in linear O(n) time.

What is the best approach for Restore the Array From Adjacent Pairs?

The optimal solution models the problem as a graph. Build an adjacency list using a hash map where each number stores its neighbors. Start from an endpoint (a node with only one neighbor) and traverse the chain while avoiding the previously visited element. This reconstructs the array in O(n) time and O(n) space.

Is Restore the Array From Adjacent Pairs asked at Google/Amazon/Meta?

This problem represents a common interview pattern involving graph modeling and adjacency reconstruction. Variants of adjacency reconstruction and path recovery appear in interviews at companies such as Amazon, Google, and Meta, especially when testing hash maps and graph traversal fundamentals.

What data structure is used in Restore the Array From Adjacent Pairs?

A hash map storing adjacency lists is the key data structure. Each value maps to a list of its neighboring numbers. The reconstructed array is obtained by traversing this graph starting from a node with degree one.

What is the time complexity of Restore the Array From Adjacent Pairs?

The optimal graph traversal solution runs in O(n) time because each pair is processed once while building the adjacency list and each element is visited exactly once during traversal. The space complexity is O(n) to store the adjacency map and the resulting array.

Comments

Now write it yourselfClose this page and solve Restore the Array From Adjacent Pairs in the editor, without looking.
Practise Restore the Array From Adjacent Pairs