Taro Logo

Restore the Array From Adjacent Pairs

#3 Most AskedMedium
155 views
Topics:
ArraysGraphs

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.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the range of values for the elements inside `adjacentPairs`, and can they include negative numbers or zeros?
  2. What is the minimum and maximum length of the `adjacentPairs` array (i.e., what is the size of the hidden array)?
  3. Since the problem states we can return the answer in any valid direction, does it matter whether we return the array in forward or reverse order?
  4. Are there any duplicate values allowed within the hidden array itself, or are all elements in the hidden array strictly unique?
  5. Is it guaranteed that the input `adjacentPairs` always forms a single continuous sequence without any disconnected components?

Brute Force Solution

Approach

Imagine you have a puzzle of connected pairs of items that have been jumbled up, and you need to line them all up in a single correct sequence. The brute force approach involves blindly guessing every single possible ordering of the items from start to finish.

Here's how the algorithm would work step-by-step:

  1. Gather all the unique items from the given pairs.
  2. Generate a complete trial sequence by lining up all these items in some arbitrary order.
  3. Check the trial sequence against the rules to see if every adjacent pair in your line actually matches one of the pairs from the original puzzle.
  4. If the sequence does not satisfy the rules, throw it away and try a completely different ordering of the items.
  5. Repeat this process of guessing an ordering and checking it against the rules.
  6. Keep going through every possible combination until you finally stumble upon the exact ordering that successfully satisfies all the adjacent pair connections.

Code Implementation

import itertools


def restore_array(adjacent_pairs):
    unique_elements = set()
    for pair in adjacent_pairs:
        unique_elements.add(pair[0])
        unique_elements.add(pair[1])

    # We generate all possible permutations because the brute force strategy requires checking every ordering
    for trial_sequence in itertools.permutations(unique_elements):
        is_valid_sequence = True

        for index in range(len(trial_sequence) - 1):
            current_pair = {trial_sequence[index], trial_sequence[index + 1]}
            found_match = False

            for original_pair in adjacent_pairs:
                if set(original_pair) == current_pair:
                    found_match = True
                    break

            if not found_match:
                is_valid_sequence = False
                break

        # We return the first sequence that satisfies all adjacent pair rules to solve the puzzle
        if is_valid_sequence:
            return list(trial_sequence)

    return []

Big(O) Analysis

Time Complexity
O(n!) – The input size n represents the number of unique items, and the cost is driven by generating and testing every possible permutation of these items. There are n factorial possible trial sequences to generate, and for each trial sequence, we must check its adjacent pairs against the original puzzle rules. This combinatorial explosion of orderings leads to approximately n factorial operations, which simplifies to the factorial time complexity of O(n!).
Space Complexity
O(n) – The auxiliary space is driven by a hash map used to store the adjacency list of every unique item and a visited set to keep track of processed locations. Additionally, the final result array stores the reconstructed sequence of length N plus one. As the number of adjacent pairs grows, these data structures scale linearly with the input size N, resulting in an overall auxiliary space complexity of O(N).

Optimal Solution

Approach

Imagine you have a puzzle where every piece tells you which two pieces must sit right next to each other, but the pieces are completely jumbled up. The best way to solve this is to first figure out where the line of pieces must start and end by finding the unique pieces that only have a single neighbor, and then simply walk down the line from one end to the other.

Here's how the algorithm would work step-by-step:

  1. Look at all the neighbor clues and keep a tally of how many neighbors each item has.
  2. Identify the special items that only have a single neighbor, because these must be the very beginning and the very end of your final line.
  3. Pick one of these end items to serve as your starting point.
  4. Look at who your current item's neighbors are, and pick the neighbor you haven't visited yet to be the next item in line.
  5. Step forward to this new item and repeat the process of finding your unvisited neighbor.
  6. Keep walking forward step by step until you reach the other end item that only has a single neighbor, meaning your entire puzzle is now correctly restored.

Code Implementation

from collections import defaultdict


def restore_array(adjacent_pairs):
    adjacency_map = defaultdict(list)
    
    for element_u, element_v in adjacent_pairs:
        adjacency_map[element_u].append(element_v)
        adjacency_map[element_v].append(element_u)

    # We identify endpoints because boundary elements only have one neighbor.
    start_element = None
    for candidate_key, neighbors in adjacency_map.items():
        if len(neighbors) == 1:
            start_element = candidate_key
            break

    restored_array = [start_element]
    current_element = start_element
    previous_element = None

    # We traverse the chain until we reach the other single-neighbor boundary.
    while len(restored_array) < len(adjacency_map):
        next_candidates = adjacency_map[current_element]
        for neighbor in next_candidates:
            if neighbor != previous_element:
                previous_element = current_element
                current_element = neighbor
                restored_array.append(current_element)
                break

    # The reconstructed sequence is returned once all adjacent pairs are walked.
    return restored_array

Big(O) Analysis

Time Complexity
O(n) – Building the adjacency map and degree count takes linear time because we iterate through the n-1 adjacent pairs to store connections in a hash map. Finding the starting endpoint takes constant time, and walking down the line visits each of the n items and their neighbors exactly once. The traversal visits n elements sequentially with constant-time hash map lookups at each step, totaling approximately 2n operations that simplify to O(n).
Space Complexity
O(n) – To restore the array, we maintain a hash map tallying the neighbors for each unique item and a visited set to track processed elements, both scaling linearly with the total number of elements N. Additionally, the final output array stores all N restored items. The recursion stack or iterative traversal path further requires space proportional to N to walk from one end to the other. Thus, the total auxiliary space complexity simplifies to Big O of N.

Edge Cases

Minimum valid input with a single adjacent pair
How to Handle:
The graph traversal correctly identifies both elements as endpoints with a degree of one and returns them in either valid order.
Negative numbers and zero values present in the input pairs
How to Handle:
Using a hash map for adjacency list construction naturally accommodates any integer value as a key without requiring coordinate offsets.
Large scale input approaching maximum constraints
How to Handle:
An adjacency map and linear traversal ensure time and space complexity remain proportional to the number of elements, preventing memory or timeout limits.
Reconstruction direction ambiguity
How to Handle:
The problem statement explicitly allows returning the array in either forward or reverse order, so either valid endpoint can serve as the starting node.
Deep recursion during graph traversal
How to Handle:
Using an iterative loop instead of recursive DFS avoids stack overflow exceptions when traversing the long linear sequence.
Elements with a degree of two versus endpoints with a degree of one
How to Handle:
Scanning the adjacency map for a node with exactly one neighbor allows us to reliably pinpoint the start of the sequence.
Duplicate values allowed across different positions in the hidden array
How to Handle:
The problem guarantees every element appears at most twice, which prevents complex branching and guarantees a strictly linear graph structure.
0/14 completed