Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to restore the array from adjacent pairs in Python
Suppose we have a 2D array called adPair of size n-1 where each adPair[i] has two elements [ui, vi] representing that the elements ui and vi are adjacent in an array called nums. In nums there are n unique elements. We have to find the array nums.
So, if the input is like adPair = [[3,2],[4,5],[4,3]], then the output will be [2,3,4,5].
Algorithm
To solve this, we will follow these steps ?
-
my_map:= an empty map to store adjacency list for different keys - for each pair (a, b) in
adPair, do- insert b at the end of
my_map[a] - insert a at the end of
my_map[b]
- insert b at the end of
- for each key a and value list l in
my_map, do- if size of l is same as 1, then
-
nums:= a list with two elements (a, l[0]) - break from loop
-
- if size of l is same as 1, then
- for i in range 1 to size of
adPair− 1, do- a, b :=
my_map[last element of nums] - if a is same as second last element of
nums, then- insert b at the end of
nums
- insert b at the end of
- otherwise,
- insert a at the end of
nums
- insert a at the end of
- a, b :=
- return
nums
How It Works
The algorithm builds an adjacency list where each element maps to its neighbors. The starting point is found by locating an element with only one neighbor (endpoint). Then we traverse the chain, avoiding backtracking by checking the previous element.
Example
Let us see the following implementation to get better understanding ?
from collections import defaultdict
def solve(adPair):
my_map = defaultdict(list)
for a, b in adPair:
my_map[a].append(b)
my_map[b].append(a)
# Find starting point (element with only one neighbor)
for a, l in my_map.items():
if len(l) == 1:
nums = [a, l[0]]
break
# Build the rest of the array
for i in range(1, len(adPair)):
a, b = my_map[nums[-1]]
if a == nums[-2]:
nums.append(b)
else:
nums.append(a)
return nums
adPair = [[3,2],[4,5],[4,3]]
print(solve(adPair))
[2, 3, 4, 5]
Step-by-Step Execution
For input [[3,2],[4,5],[4,3]] ?
from collections import defaultdict
def solve_with_steps(adPair):
my_map = defaultdict(list)
# Build adjacency list
for a, b in adPair:
my_map[a].append(b)
my_map[b].append(a)
print("Adjacency list:", dict(my_map))
# Find starting point
for a, l in my_map.items():
if len(l) == 1:
nums = [a, l[0]]
print(f"Starting with: {nums}")
break
# Build rest of array
for i in range(1, len(adPair)):
a, b = my_map[nums[-1]]
print(f"Neighbors of {nums[-1]}: [{a}, {b}]")
if a == nums[-2]:
nums.append(b)
print(f"Added {b}, nums: {nums}")
else:
nums.append(a)
print(f"Added {a}, nums: {nums}")
return nums
adPair = [[3,2],[4,5],[4,3]]
result = solve_with_steps(adPair)
print(f"Final result: {result}")
Adjacency list: {3: [2, 4], 2: [3], 4: [5, 3], 5: [4]}
Starting with: [2, 3]
Neighbors of 3: [2, 4]
Added 4, nums: [2, 3, 4]
Neighbors of 4: [5, 3]
Added 5, nums: [2, 3, 4, 5]
Final result: [2, 3, 4, 5]
Conclusion
The solution uses graph traversal to reconstruct the original array from adjacent pairs. We identify the starting endpoint and traverse the chain while avoiding backtracking to build the complete sequence.
