Frequency Game | GeeksForGeeks Problem of the Day | 31May
Given an array A of size N. The elements of the array consist of positive integers. You have to find the largest element with minimum frequency.
Example 1:
Input: 5 2 2 5 50 1 Output: 50 Explanation : All elements are having frequency 1 except 2. 50 is the maximum element with minimum frequency.
Example 2:
Input:
4
3 3 5 5
Output:
5
Explanation:
Both 3 and 5 have the same frequency, so 5 should be returned.
User Task:
Your task is to complete the provided function LargButMinFreq(A, n) which accepts array A and n. Hence you have to return the largest element with minimum frequency.
Expected Time Complexity: O(N)
Expected Space Complexity: O(N)
Constraints:
1 <= N <= 105
1 <= A[i] <= 106
SOLUTION(in C++) -
//{ Driver Code Starts
// Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
class Solution{
public:
int LargButMinFreq(int a[], int n) {
// code here
map<int, int> m;
for(int i =0;i<n;i++){
m[a[i]]++;
}
int mini = INT_MAX;
for(auto i : m){
if(i.second<mini){
mini = i.second;
}
}
int maxi = INT_MIN;
for(auto i:m){
if(i.second == mini && i.first > maxi){
maxi = i.first;
}
}
return maxi;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
// Iterating over testcases
while (t--) {
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) cin >> arr[i];
Solution ob;
cout << ob.LargButMinFreq(arr, n) << endl;
}
}
// } Driver Code Ends
Comments
Post a Comment