Restore the Array From Adjacent Pairs

Medium

Topics
ArrayHash Table

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

pairs2 – 13 – 43 – 2
array1234null
a neighbouring pair, order unknownan end of the array
Each chip says two values were neighbours in the original array, but not which came first and not where the pair sat. Exactly two values turn up in only one chip, and those have to be the two ends — 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.
The values are distinct, so a value never appears in two different places.
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

pairs4 – -21 – 4-3 – 1
array-314-2null
a neighbouring pair, order unknownan end of the array
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

pairs100 – -100
array-100100null
a neighbouring pair, order unknownan end of the array
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

  1. Build an adjacency map from the pairs.
  2. Find the values whose adjacency list has length 1 — there are exactly two — and start from the smaller of them.
  3. Walk: append the current value, then move to whichever neighbour is not the previous value.
  4. Stop when n values 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 out
SensAI
Beta
Tap the mic to stop voice mode