## Similar Problems

Similar Problems not available

# Most Frequent Even Element - Leetcode Solution

## Companies:

LeetCode: Most Frequent Even Element Leetcode Solution

Difficulty: Easy

Topics: hash-table array

Problem Statement:

Given an integer array nums, return the most frequent element that is even. If there are multiple elements that appear most frequently, return the one with the smallest value.

Examples:

Input: nums = [1,2,3,2] Output: 2

Input: nums = [2,2,2,1,1,3] Output: 2

Approach:

In this problem, we need to count the frequency of even numbers present in the given array. If there are multiple elements with the same maximum frequency, we need to return the smallest of these elements.

We can solve this problem by iterating over the array and keeping a count of the even numbers we encounter. We can use a hash table to keep track of the frequency of each even number. Then we can find the even number with the highest frequency and return it. If there are multiple even numbers with the same highest frequency, we can return the smallest of these numbers.

Algorithm:

- Initialize a hash table to count the frequency of even numbers.
- For each element in the array, check if it is even. If it is, update the frequency count for that even number in the hash table.
- Find the even number with the highest frequency in the hash table.
- If there are multiple even numbers with the same highest frequency, return the smallest of these numbers.

Code:

Python:

class Solution: def findMostFrequentEven(self, nums: List[int]) -> int: freq = {} max_freq = 0 max_even = 0

```
for num in nums:
if num % 2 == 0:
if num in freq:
freq[num] += 1
else:
freq[num] = 1
if freq[num] > max_freq:
max_freq = freq[num]
max_even = num
elif freq[num] == max_freq:
max_even = min(max_even, num)
return max_even
```

Complexity Analysis:

Time Complexity: O(N), where N is the length of the input array nums. We iterate over the array once to count the frequency of even numbers.

Space Complexity: O(N), we use a hash table to keep track of the frequency of even numbers. In the worst case, all elements in the array are even and distinct, and therefore, the hash table will have N key-value pairs.

## Most Frequent Even Element Solution Code

`1`