Generate an array from given pairs of adjacent elements

Given a 2D array arr[][] consisting of N pairs of integers such that the two elements in each row indicates that they are adjacent elements in the original array. The task is to construct an array with given pairs of adjacent elements of arr[].
Examples
Input: arr[] = {{5, 1 }, {3, 4 }, {3, 5}}Â
Output: 4 3 5 1Â
Explanation: The array can be constructed using the following operations:Â
Operation 1: The elements 4 and 1 have a single neighbor. Therefore, they can either be the first or last elements in the original array. Considering 4 to be the first element in the original array, A[] = {4}.Â
Operation 2: Place 3 adjacently to 4. Therefore, A[] = {4, 3}Â
Operation 3: Place 5 adjacently to 3. Therefore, A[] = {4, 3, 5}.Â
Operation 4: Place 1 as the last element in the array. Therefore, A[] = {4, 3, 5, 1}.Input: arr[] = {{8, 11}, {-3, 6}, {-3, 8}}Â
Output: 6 -3 8 11
Approach: The problem can be solved using Hashing and DFS. Follow the steps below to solve the problem:
- Initialize an adjacency list using a Map, say mp, to store assign neighbouring elements to each element.
- Initialize a vector, say res, to store the original elements in the array.
- Start creating the original array from the corner elements. Therefore, find the elements which have only one neighbor. This can be either the first or the last element of the original array.
- Insert the obtained element in res.
- Traverse through every element in the adjacency list and check if its neighbor(s) are visited or not.
- Insert the unvisited neighbours in the vector res and traverse through all the neighbors of that element. Repeat step 5 till all elements are visited.
- Return res.
Below is the implementation of the above approach:
C++
// C++ program of the above approach#include <bits/stdc++.h>using namespace std;Â
// Utility function to find original arrayvoid find_original_array(vector<pair<int, int> >& A){Â
    // Map to store all neighbors for each element    unordered_map<int, vector<int> > mp;Â
    // Vector to store original elements    vector<int> res;Â
    // Stotrs which array elements are visited    unordered_map<int, bool> visited;Â
    // Adjacency list to store neighbors    // of each array element    for (auto& it : A) {Â
        mp[it.first].push_back(it.second);        mp[it.second].push_back(it.first);    }Â
    auto it = mp.begin();Â
    // Find the first corner element    for (; it != mp.end(); it++) {        if (it->second.size() == 1) {            break;        }    }Â
    // Stores first element of    // the original array    int adjacent = it->first;  Â
    // Push it into the original array    res.push_back(it->first);Â
    // Mark as visited    visited[it->first] = true;Â
    // Traversing the neighbors and check    // if the elements are visited or not    while (res.size() != A.size() + 1) {Â
        // Traverse adjacent elements        for (auto& elements : mp[adjacent]) {Â
            // If element is not visited            if (!visited[elements]) {Â
                // Push it into res                res.push_back(elements);Â
                // Mark as visited                visited[elements] = true;Â
                // Update the next adjacent                adjacent = elements;            }        }    }Â
    // Print original array    for (auto it : res) {        cout << it << " ";    }}Â
// Driver Codeint main(){Â
    // Given pairs of adjacent elements    vector<pair<int, int> > A        = { { 5, 1 }, { 3, 4 }, { 3, 5 } };Â
    find_original_array(A);    return 0;} |
Java
// Java program of the above approachimport java.io.*;import java.util.*;Â
class Pair {Â Â Â Â int first, second;Â Â Â Â Pair(int first, int second)Â Â Â Â {Â Â Â Â Â Â Â Â this.first = first;Â Â Â Â Â Â Â Â this.second = second;Â Â Â Â }}Â
class GFG {    // Utility function to find original array    static void find_original_array(List<Pair> A)    {Â
        // Map to store all neighbors for each element        @SuppressWarnings("unchecked")        Map<Integer, List<Integer> > mp = new HashMap();Â
        // Vector to store original elements        List<Integer> res = new ArrayList<Integer>();Â
        // Stotrs which array elements are visited        @SuppressWarnings("unchecked")        Map<Integer, Boolean> visited = new HashMap();Â
        // Adjacency list to store neighbors        // of each array element        for (Pair it : A) {            List<Integer> temp;            temp = (mp.containsKey(it.first))                       ? mp.get(it.first)                       : new ArrayList<Integer>();            temp.add(it.second);            mp.put(it.first, temp);Â
            temp = (mp.containsKey(it.second))                       ? mp.get(it.second)                       : new ArrayList<Integer>();            temp.add(it.first);            mp.put(it.second, temp);        }Â
        int it = 0;Â
        // Find the first corner element        for (Map.Entry<Integer, List<Integer> > entry :             mp.entrySet()) {            if (entry.getValue().size() == 1) {                it = entry.getKey();            }        }Â
        // Stores first element of        // the original array        int adjacent = it;Â
        // Push it into the original array        res.add(it);Â
        // Mark as visited        visited.put(it, true);Â
        // Traversing the neighbors and check        // if the elements are visited or not        while (res.size() != A.size() + 1) {Â
            // Traverse adjacent elements            for (int elements : mp.get(adjacent)) {Â
                // If element is not visited                if (!visited.containsKey(elements)) {Â
                    // Push it into res                    res.add(elements);Â
                    // Mark as visited                    visited.put(elements, true);Â
                    // Update the next adjacent                    adjacent = elements;                }            }        }Â
        // Print original array        for (int val : res) {            System.out.print(val + " ");        }    }    // Driver Code    public static void main(String[] args)    {        @SuppressWarnings("unchecked")        List<Pair> A = new ArrayList();        A.add(new Pair(5, 1));        A.add(new Pair(3, 4));        A.add(new Pair(3, 5));Â
        find_original_array(A);    }}Â
// This code is contributed by jithin. |
Python3
# Python3 program of the above approachÂ
# Utility function to find original arraydef find_original_array(A):Â
    # Map to store all neighbors for each element    mp = [[] for i in range(6)]Â
    # Vector to store original elements    res = []Â
    # Stotrs which array elements are visited    visited = {}Â
    # A djacency list to store neighbors    # of each array element    for it in A:        mp[it[0]].append(it[1])        mp[it[1]].append(it[0])Â
    start = 0Â
    # Find the first corner element    for it in range(6):        if (len(mp[it]) == 1):            start = it + 3            breakÂ
    # Stores first element of    # the original array      adjacent = startÂ
    # Push it into the original array    res.append(start)Â
    # Mark as visited    visited[start] = TrueÂ
    # Traversing the neighbors and check    # if the elements are visited or not    while (len(res) != len(A) + 1):Â
        # Traverse adjacent elements        for elements in mp[adjacent]:Â
            # If element is not visited            if (elements not in visited):Â
                # Push it into res                res.append(elements)Â
                # Mark as visited                visited[elements] = TrueÂ
                # Update the next adjacent                adjacent = elementsÂ
    # Print original array    print(*res)Â
# Driver Codeif __name__ == '__main__':Â
    # Given pairs of adjacent elements    A = [[5, 1],[ 3, 4],[ 3, 5]]Â
    find_original_array(A)Â
# This code is contributed by mohit kumar 29. |
C#
// C# program of the above approachusing System;using System.Collections.Generic;Â
public class Pair {Â Â public int first, second;Â Â public Pair(int first, int second)Â Â {Â Â Â Â this.first = first;Â Â Â Â this.second = second;Â Â }}Â
public class GFG{Â
  // Utility function to find original array  static void find_original_array(List<Pair> A)  {Â
    // Map to store all neighbors for each element    Dictionary<int,List<int>> mp = new Dictionary<int,List<int>>();Â
    // Vector to store original elements    List<int> res = new List<int>();Â
    // Stotrs which array elements are visited    Dictionary<int,bool> visited = new Dictionary<int,bool>();Â
    // Adjacency list to store neighbors    // of each array element    foreach (Pair it in A)    {      List<int> temp;      temp = (mp.ContainsKey(it.first))        ? mp[it.first]        : new List<int>();Â
      temp.Add(it.second);      if(!mp.ContainsKey(it.first))        mp.Add(it.first, temp);      else        mp[it.first] = temp;Â
      temp = (mp.ContainsKey(it.second))        ? mp[it.second]        : new List<int>();      temp.Add(it.first);      if(!mp.ContainsKey(it.second))        mp.Add(it.second, temp);      else        mp[it.second] = temp;Â
Â
    }Â
    int It = 0;Â
    // Find the first corner element    foreach (int key in mp.Keys)    {      if(mp[key].Count == 1)      {        It=key;      }    }Â
    // Stores first element of    // the original array    int adjacent = It;Â
    // Push it into the original array    res.Add(It);Â
    // Mark as visited    visited.Add(It, true);Â
    // Traversing the neighbors and check    // if the elements are visited or not    while (res.Count != A.Count + 1)    {Â
      // Traverse adjacent elements      foreach (int elements in mp[adjacent])      {Â
        // If element is not visited        if (!visited.ContainsKey(elements))         {Â
          // Push it into res          res.Add(elements);Â
          // Mark as visited          visited.Add(elements, true);Â
          // Update the next adjacent          adjacent = elements;        }      }    }Â
    // Print original array    foreach (int val in res)    {      Console.Write(val + " ");    }  }Â
  // Driver Code  static public void Main (){    List<Pair> A = new List<Pair>();    A.Add(new Pair(5, 1));    A.Add(new Pair(3, 4));    A.Add(new Pair(3, 5));Â
    find_original_array(A);  }}Â
// This code is contributed by avanitrachhadiya2155 |
Javascript
<script>Â
// JavaScript program of the above approachÂ
// Utility function to find original arrayfunction find_original_array(A){Â
    // Map to store all neighbors for each element    let mp = new Array(6).fill(0).map(()=>[])Â
    // Vector to store original elements    let res = []Â
    // Stotrs which array elements are visited    let visited = new Map();Â
    // A djacency list to store neighbors    // of each array element    for(let it of A){        mp[it[0]].push(it[1])        mp[it[1]].push(it[0])    }Â
    let start = 0Â
    // Find the first corner element    for(let it=0;it<6;it++){        if (mp[it].length == 1){            start = it + 3            break        }    }Â
    // Stores first element of    // the original array    let adjacent = startÂ
    // Push it into the original array    res.push(start)Â
    // Mark as visited    visited.set(start , true)Â
    // Traversing the neighbors and check    // if the elements are visited or not    while (res.length != A.length + 1){Â
        // Traverse adjacent elements        for(let elements of mp[adjacent]){Â
            // If element is not visited            if (!visited.has(elements)){Â
                // Push it into res                res.push(elements)Â
                // Mark as visited                visited.set(elements , true)Â
                // Update the next adjacent                adjacent = elements            }        }    }Â
    // Print original array    for(let i of res){        document.write(i," ");    }}Â
// Driver CodeÂ
// Given pairs of adjacent elementslet A = [[5, 1],[ 3, 4],[ 3, 5]]Â
find_original_array(A)Â
// This code is contributed by shinjanpatraÂ
</script> |
4 3 5 1
Â
Time complexity: O(N2)Â
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



