Restore the Array From Adjacent Pairs
Medium
Topics
There is an array of n distinct integers that you do not have. What you have is edges, a list of all n - 1 adjacent pairs from it, in no particular order and with each pair in no particular order.
Reconstruct the array.
An array and its reverse produce the same set of adjacent pairs, so both are valid reconstructions. Return the lexicographically smaller of the two, which makes the answer unique.
Example 1
1 and 4 here, shaded in the lower row. Reversing the array gives [4,3,2,1], which fits every pair just as well, so the statement asks for the lexicographically smaller of the two and that is the one shown.Input: edges = [[2,1],[3,4],[3,2]] Output: [1,2,3,4] Explanation: The chain is 1-2-3-4. Its reverse [4,3,2,1] is equally valid, and 1 < 4 so this one wins.
Example 2
Input: edges = [[4,-2],[1,4],[-3,1]] Output: [-3,1,4,-2] Explanation: The chain is -2-4-1--3 or its reverse; the reverse starts with -3, which is smaller than -2.
Example 3
Input: edges = [[100,-100]] Output: [-100,100] Explanation: Two elements and one pair; the smaller goes first.
Constraints
- n == edges.length + 1
- 1 <= edges.length <= 10^5
- The pairs are exactly the adjacent pairs of some array of distinct integers
Editorial — intuition, approach, complexity and pitfalls
Intuition
Treat each value as a vertex and each pair as an edge. The original array is a path, so this graph is a path too — which means every value has degree 2 except the two ends, which have degree 1.
That is the whole insight: the ends are identifiable without reconstructing anything, because they are the only values appearing in exactly one pair. Pick an end and walk, and at each step the next value is the neighbour you did not just come from — there is only ever one, because the degree is 2.
The ambiguity is real and limited: the two ends are interchangeable, so there are exactly two reconstructions and they are reverses of each other. Starting from the smaller end does not settle it — the array starting with the smaller end may still be the lexicographically larger of the two, since comparison continues past the first element only when they tie, which distinct values never do. So starting from the smaller end is sufficient here.
The single-pair case is where the degree argument degenerates pleasantly: both values have degree 1, and either is an end.
Approach
- Build an adjacency map from the pairs.
- Find the values whose adjacency list has length 1 — there are exactly two — and start from the smaller of them.
- Walk: append the current value, then move to whichever neighbour is not the previous value.
- Stop when
nvalues have been placed.
Walkthrough
edges = [[4,-2],[1,4],[-3,1]]
adjacency
4: -2, 1
-2: 4
1: 4, -3
-3: 1
degree 1: -2 and -3, so those are the ends
the smaller end is -3, so start there
walk
-3 previous none, neighbour 1
1 previous -3, neighbours 4 and -3 -> take 4
4 previous 1, neighbours -2 and 1 -> take -2
-2 previous 4, nothing left
answer [-3, 1, 4, -2]
Starting from -2 instead gives [-2, 4, 1, -3], the reverse,
which is lexicographically larger at the very first element.Complexity
- Time — O(n): the adjacency map is built in one pass and the walk takes one step per element.
- Space — O(n): the adjacency map.
Common Pitfalls
- Starting from an arbitrary value. Starting anywhere other than an end produces a walk that runs off one side and never covers the array.
- Starting from either end without the tie-break. Both walks are valid reconstructions, and only one is the expected answer.
- Tracking visited values instead of just the previous one. It works, and the previous value is all that is needed since the degree is at most 2 — and with distinct values there is no ambiguity.
- Assuming the pairs are given in order, or that each pair is ordered. Neither is true.
Full Solution — all languages
class Solution:
def restoreArray(self, edges):
neighbours = {}
for a, b in edges:
neighbours.setdefault(a, []).append(b)
neighbours.setdefault(b, []).append(a)
ends = sorted(v for v, adj in neighbours.items() if len(adj) == 1)
out = [ends[0]]
previous = None
while len(out) < len(edges) + 1:
current = out[-1]
nxt = next(v for v in neighbours[current] if v != previous)
out.append(nxt)
previous = current
return outimport java.util.*;
class Solution {
public int[] restoreArray(int[][] edges) {
Map<Integer, List<Integer>> neighbours = new HashMap<>();
for (int[] e : edges) {
neighbours.computeIfAbsent(e[0], x -> new ArrayList<>()).add(e[1]);
neighbours.computeIfAbsent(e[1], x -> new ArrayList<>()).add(e[0]);
}
List<Integer> ends = new ArrayList<>();
for (Map.Entry<Integer, List<Integer>> e : neighbours.entrySet()) {
if (e.getValue().size() == 1) ends.add(e.getKey());
}
Collections.sort(ends);
int[] out = new int[edges.length + 1];
out[0] = ends.get(0);
Integer previous = null;
for (int at = 1; at < out.length; at++) {
int current = out[at - 1];
for (int v : neighbours.get(current)) {
if (previous == null || v != previous) {
out[at] = v;
break;
}
}
previous = current;
}
return out;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<int> restoreArray(vector<vector<int>>& edges) {
map<int, vector<int>> neighbours;
for (auto& e : edges) {
neighbours[e[0]].push_back(e[1]);
neighbours[e[1]].push_back(e[0]);
}
vector<int> ends;
for (auto& kv : neighbours) if (kv.second.size() == 1) ends.push_back(kv.first);
sort(ends.begin(), ends.end());
vector<int> out {
ends[0]
};
bool first = true;
int previous = 0;
while (out.size() < edges.size() + 1) {
int current = out.back();
for (int v : neighbours[current]) {
if (first || v != previous) {
out.push_back(v);
break;
}
}
previous = current;
first = false;
}
return out;
}
};/**
* @param {number[][]} edges
* @return {number[]}
*/ var restoreArray = function(edges) {
const neighbours = new Map();
for (const e of edges) {
if (!neighbours.has(e[0])) neighbours.set(e[0], []);
if (!neighbours.has(e[1])) neighbours.set(e[1], []);
neighbours.get(e[0]).push(e[1]);
neighbours.get(e[1]).push(e[0]);
}
const ends = [...neighbours.keys()].filter(v => neighbours.get(v).length === 1) .sort((x, y) => x - y);
const out = [ends[0]];
let previous = null;
while (out.length < edges.length + 1) {
const current = out[out.length - 1];
const next = neighbours.get(current).find(v => v !== previous);
out.push(next);
previous = current;
}
return out;
};