Leetcode 1743: Restore the Array From Adjacent Pairs

grid47
grid47
Exploring patterns and algorithms
May 16, 2024 7 min read

You are given an integer array nums with 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 where each adjacentPairs[i] = [ui, vi] indicates that the elements ui and vi are adjacent in nums. Your task is to reconstruct the original array nums using these adjacent pairs. There could be multiple valid solutions, so return any one of them.
Problem
Approach
Steps
Complexity
Input: You are given an array `adjacentPairs` containing n - 1 pairs where each pair represents two adjacent elements of the original array `nums`.
Example: Input: adjacentPairs = [[1,2], [2,3], [4,2]]
Constraints:
• nums.length == n
• adjacentPairs.length == n - 1
• adjacentPairs[i].length == 2
• 2 <= n <= 10^5
• -10^5 <= nums[i], ui, vi <= 10^5
Output: Return the reconstructed original array `nums`.
Example: Output: [1, 2, 3, 4]
Constraints:
• The solution should be reconstructed based on the given adjacent pairs.
Goal: The goal is to reconstruct the array `nums` using the adjacent pairs and determine the correct order of the elements.
Steps:
• 1. Create a map to store the adjacency list of each element.
• 2. Identify the element with only one adjacent element, as this is either the first or last element of `nums`.
• 3. Starting from that element, iteratively build the array by moving to the next adjacent element until the entire array is reconstructed.
Goal: The problem guarantees that every adjacent pair exists and can be used to reconstruct the original array.
Steps:
• The array will always contain a valid solution that can be reconstructed using the adjacent pairs.
Assumptions:
• The given pairs are valid and consistent, allowing for the reconstruction of the array.
Input: Input: adjacentPairs = [[1,2], [2,3], [4,2]]
Explanation: The pairs tell us that 1 and 2 are adjacent, 2 and 3 are adjacent, and 2 and 4 are adjacent. This allows us to reconstruct the array as [1, 2, 3, 4].

Input: Input: adjacentPairs = [[4,-2],[1,4],[-3,1]]
Explanation: The adjacent pairs indicate that the array could be [-2, 4, 1, -3], as 4 and 1 are adjacent, 1 and -3 are adjacent, and 4 and -2 are adjacent.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus