Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map
[[2,1],[3,4],[3,2]]
[[4,-2],[1,4],[-3,1]]
[[100000,-100000]]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1743: Restore the Array From Adjacent Pairs
class Solution {
public int[] restoreArray(int[][] adjacentPairs) {
int n = adjacentPairs.length + 1;
Map<Integer, List<Integer>> g = new HashMap<>();
for (int[] e : adjacentPairs) {
int a = e[0], b = e[1];
g.computeIfAbsent(a, k -> new ArrayList<>()).add(b);
g.computeIfAbsent(b, k -> new ArrayList<>()).add(a);
}
int[] ans = new int[n];
for (Map.Entry<Integer, List<Integer>> entry : g.entrySet()) {
if (entry.getValue().size() == 1) {
ans[0] = entry.getKey();
ans[1] = entry.getValue().get(0);
break;
}
}
for (int i = 2; i < n; ++i) {
List<Integer> v = g.get(ans[i - 1]);
ans[i] = v.get(1) == ans[i - 2] ? v.get(0) : v.get(1);
}
return ans;
}
}
// Accepted solution for LeetCode #1743: Restore the Array From Adjacent Pairs
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
}
# Accepted solution for LeetCode #1743: Restore the Array From Adjacent Pairs
class Solution:
def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:
g = defaultdict(list)
for a, b in adjacentPairs:
g[a].append(b)
g[b].append(a)
n = len(adjacentPairs) + 1
ans = [0] * n
for i, v in g.items():
if len(v) == 1:
ans[0] = i
ans[1] = v[0]
break
for i in range(2, n):
v = g[ans[i - 1]]
ans[i] = v[0] if v[1] == ans[i - 2] else v[1]
return ans
// Accepted solution for LeetCode #1743: Restore the Array From Adjacent Pairs
struct Solution;
use std::collections::HashMap;
use std::collections::HashSet;
impl Solution {
fn restore_array(adjacent_pairs: Vec<Vec<i32>>) -> Vec<i32> {
let mut adj: HashMap<i32, HashSet<i32>> = HashMap::new();
let mut nodes: HashSet<i32> = HashSet::new();
for pair in adjacent_pairs {
let u = pair[0];
let v = pair[1];
adj.entry(u).or_default().insert(v);
adj.entry(v).or_default().insert(u);
nodes.insert(u);
nodes.insert(v);
}
let mut res = vec![];
let mut u = *adj
.iter()
.filter(|(_, edges)| edges.len() == 1)
.map(|(u, _)| u)
.min()
.unwrap();
res.push(u);
while adj[&u].len() == 1 {
let v = *adj[&u].iter().next().unwrap();
adj.get_mut(&u).unwrap().remove(&v);
adj.get_mut(&v).unwrap().remove(&u);
res.push(v);
u = v;
}
res
}
}
#[test]
fn test() {
let adjacent_pairs = vec_vec_i32![[2, 1], [3, 4], [3, 2]];
let res = vec![1, 2, 3, 4];
assert_eq!(Solution::restore_array(adjacent_pairs), res);
let adjacent_pairs = vec_vec_i32![[4, -2], [1, 4], [-3, 1]];
let res = vec![-3, 1, 4, -2];
assert_eq!(Solution::restore_array(adjacent_pairs), res);
let adjacent_pairs = vec_vec_i32![[100000, -100000]];
let res = vec![-100000, 100000];
assert_eq!(Solution::restore_array(adjacent_pairs), res);
}
// Accepted solution for LeetCode #1743: Restore the Array From Adjacent Pairs
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #1743: Restore the Array From Adjacent Pairs
// class Solution {
// public int[] restoreArray(int[][] adjacentPairs) {
// int n = adjacentPairs.length + 1;
// Map<Integer, List<Integer>> g = new HashMap<>();
// for (int[] e : adjacentPairs) {
// int a = e[0], b = e[1];
// g.computeIfAbsent(a, k -> new ArrayList<>()).add(b);
// g.computeIfAbsent(b, k -> new ArrayList<>()).add(a);
// }
// int[] ans = new int[n];
// for (Map.Entry<Integer, List<Integer>> entry : g.entrySet()) {
// if (entry.getValue().size() == 1) {
// ans[0] = entry.getKey();
// ans[1] = entry.getValue().get(0);
// break;
// }
// }
// for (int i = 2; i < n; ++i) {
// List<Integer> v = g.get(ans[i - 1]);
// ans[i] = v.get(1) == ans[i - 2] ? v.get(0) : v.get(1);
// }
// return ans;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.