Problem Description
Given a list of adjacent pairs, where each pair represents two consecutive elements from an unknown array of unique integers, restore the original array. Each pair can appear in any order, and the endpoints of the array (which have only one adjacent neighbor) must be identified to begin reconstruction.
Key Insights
- The array forms a chain-like structure.
- All elements except the endpoints appear in exactly two pairs.
- Endpoints are the elements that appear only once.
- Use a hashmap (adjacency list) to track neighbors.
- Traverse the chain starting from an endpoint, avoiding backtracking, to reconstruct the original array.
Space and Time Complexity
Time Complexity: O(n) - We traverse the list of pairs and then reconstruct the array in one pass. Space Complexity: O(n) - We store all the elements and their neighbors in a hashmap and the final array.
Solution
We first create a hashmap to map each element to its adjacent elements. Since the endpoints are unique in that they only have one neighbor, we locate one of them to serve as the start of our traversal. Then, we iteratively traverse from the current element to its neighbor (ignoring the element we just came from) until we reconstruct the entire array. This approach works efficiently given the constraints.