Wednesday, 27 Oct 2021

# Generate an N-length array having GCD of all its pairs present in a given 2D array

Given a 2D array arr[][] consisting of N*N positive integers, the task is to generate an N-length array such that Greatest Common Divisors(GCD) of all possible pairs of that array is present in the array arr[][].Examples:Input: N = 4, arr[] = {2, 1, 2, 3, 4, 3, 2, 6, 1, 1, 2, 2, 1, 2, 3, 2}Output: 4, 3, 6, 2Explanation:Considering the array A[] as {4, 3, 6, 2}, then the GCD of all possible pairs of this array is given below which is the given array arr[].{{4, 1, 2, 2},{1, 3, 3, 1},{2, 3, 6, 2},{2, 1, 2, 2}}Input: N = 1, mat = {100}Output: 100Approach: The above problem can be solved by using the fact that, GCD of the largest element in the original array with itself is the largest in the arr[] and after removing the gcd pairs with that element, the next element can be found. Follow the steps below to solve the given problem:Initialize a map say, M store the frequency of negation of array element in the map M.Initialize a variable, say pos as (N – 1).Now, for all array elements arr[] find the maximum element.Traverse the map M.For each element of the original array, find the element with the maximum frequency and store it in the ans.Find ans[pos] and remove all GCD from pos+1 to N-1 of the ans.Update pos as pos-1.Repeat above steps to find all elements of the original array.Finally, print the ans.Below is the implementation of the above approach:C++#include using namespace std;int n;  int gcd(int a, int b){    return b == 0 ? a : gcd(b, a % b);}  void restoreArray(vector mat){    map cnt;          vector ans(n);      for (int i = 0; i < (n * n); ++i) {                          cnt[-mat[i]]++;    }      int pos = n - 1;      for (auto it = cnt.begin();         it != cnt.end(); ++it) {          int x = -it->first;        while (it->second) {                          ans[pos] = x;            –it->second;                                      for (int i = pos + 1; i < n; ++i)                  cnt[-gcd(ans[pos], ans[i])] -= 2;                          pos--;        }    }          for (int i = 0; i < n; ++i)        printf("%d ", ans[i]);}  int main(){          n = 4;    vector mat{ 2, 1, 2, 3, 4, 3,                     2, 6, 1, 1, 2,                     2, 1, 2, 3, 2 };          restoreArray(mat);    return 0;}Output: 2 3 4 6 Time Complexity: O(N2LogN)Auxiliary Space: O(N2)Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.