Program to restore the array from adjacent pairs in Python

PythonServer Side ProgrammingProgramming

Suppose we have a 2D array called adPair of size n-1 where each adPair[i] has two elements [ui, vi] represents 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. If there are multiple solutions, return any of them.

So, if the input is like adPair = [[3,2],[4,5],[4,3]], then the output will be [2,3,4,5]

To solve this, we will follow these steps −

  • my_map := an empty map to store 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]
  • 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])
      • come out from loop
  • 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
    • otherwise,
      • insert a at the end of nums
  • return nums

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)

   for a, l in my_map.items():
      if len(l) == 1:
         nums = [a, l[0]]
         break
   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))

Input

[[3,2],[4,5],[4,3]]

Output

[2, 3, 4, 5]
raja
Published on 07-Oct-2021 11:39:28
Advertisements