Find GCD of most occurring and least occurring elements of given Array
Given an array arr[] of size n, The task is to find the GCD of the highest and lowest frequency element in the given array.
Examples:
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: arr[] = {2, 2, 4, 4, 5, 5, 6, 6, 6, 6}
Output: 2
Explanation: The frequency of the elements in the above array is
freq(2) = 2,
freq(4) = 2,
freq(5) = 2,
freq(6) = 4,
The minimum frequency is 2 (of elements 2, 4, and 5). So 2 will be picked as the least among 2, 4, and 5.
The largest frequency is 4 (of element 6).
Hence GCD of 2 and 6 = gcd(2, 6) is 2.Input: arr[] = {3, 2, 2, 44, 44, 44, 44}
Output: 1
Approach: The idea is to count the frequencies of all elements and store them in a vector and then find the gcd of the highest occurring and the least occurring elements.
Below is the implementation of the above approach:
C++14
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find frequency and find gcdint find_gcd(vector<int> v, int n){ map<int, int> mp; // Update the frequency for (int i = 0; i < n; i++) { mp[v[i]]++; } int mini = v[0], maxi = v[0]; for (auto it : mp) { mini = mp[mini] < it.second ? it.first : mini; } for (auto it : mp) { maxi = mp[maxi] > it.second ? it.first : maxi; } // Find gcd int res = __gcd(mini, maxi); return res;} // Drive Codeint main(){ vector<int> v = { 2, 2, 4, 4, 5, 5, 6, 6, 6, 6 }; int n = v.size(); cout << find_gcd(v, n) << endl; vector<int> v1 = { 3, 2, 2, 44, 44, 44, 44 }; cout << find_gcd(v1, v1.size()) << endl; return 0;} |
2 1
Time Complexity: O(n*log(n))
Auxiliary Space: O(n)


