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 −
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] 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))
[2, 3, 4, 5]