# Leetcode 2404: Most Frequent Even Element Solution

Here, we will see how to solve Most Frequent Even Element Solution of leet code 2404 problem with code and algorithm.

You are given an integer array `nums` and have to return the most frequent even element in the given array.

If there is a tie then return the smallest one. If there is no such element, return `-1`.

Example:

```1)
Input: nums = [0,1,2,2,4,4,1]
Output: 2
Explanation: The even elements are 0, 2, and 4. Of these, 2 and 4 appear the most.
We return the smallest one, which is 2.

2)
Input: nums = [4,4,4,9,2,4]
Output: 4
Explanation: 4 is the even element appears the most.

3)
Input: nums = [29,47,21,41,13,37,25,7]
Output: -1
Explanation: There is no even element.

4)
Input: nums = [0,1,2,2,8,8,8,1]
Output: 8
Explanation: The even elements are 0, 2, and 8. 8 is the even element appears the most.```

## Most Frequent Even Element Solution code in C++

Code 1:

```#include <iostream>
#include <vector>
#include <map>

using namespace std;

int mostFrequentEven(vector<int>& nums) {
map<int, int> m;
int max = -1, max_ele = -1;

for(int i = 0; i < nums.size(); i++) {
// Check if number is even
if((nums[i] & 1) == 0) {
m[nums[i]] += 1;
}
}
for(auto it : m) {
if(max < it.second) {
max = it.second;
max_ele = it.first;
}
}
return max_ele;
}

int main()
{
vector<int> v = {0,1,2,2,4,4,1};

cout<<mostFrequentEven(v);

return 0;
}```

Code 2:

```#include <iostream>
#include <vector>
#include <unordered_map>

using namespace std;

int mostFrequentEven(vector<int>& nums) {
int ans = -1;
unordered_map<int, int> count;

for (int num : nums) {
if (num & 1)
continue;
const int newCount = ++count[num];
const int maxCount = count[ans];
if (newCount > maxCount || newCount == maxCount && num < ans)
ans = num;
}

return ans;
}

int main()
{
vector<int> v = {0,1,2,2,4,4,1};

cout<<mostFrequentEven(v);

return 0;
}```

Output:

`2`

To check more leetcode problem’s solution. Pls click given below link:

https://www.techieindoor.com/category/leetcode/

Posted in C++, Easy, Leetcode