Skip to main content

Most Frequent Even Element

Problem Statement​

Problem Description​

Given an integer array nums, return the most frequent even element.

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

Examples​

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.

Example 2​

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

Example 3​

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

Constraints​

- 1 <= nums.length <= 2000

  • 0 <= nums[i] <= 105

Solution of Given Problem​

Intuition and Approach​

The problem can be solved using a brute force approach or an optimized Technique.

Approach 1:Brute Force (Naive)​

Brute Force Approach: Iterate through the array and count the frequency of each even number using a dictionary or a similar data structure. Iterate through the frequency map to find the even number with the highest frequency. In case of a tie, select the smallest even number.

Codes in Different Languages​

Written by @AmruthaPariprolu
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;

int mostFrequentEven(vector<int>& nums) {
unordered_map<int, int> freq;
for (int num : nums) {
if (num % 2 == 0) {
freq[num]++;
}
}

int maxFreq = 0;
int res = -1;
for (auto& [num, count] : freq) {
if (count > maxFreq || (count == maxFreq && num < res)) {
maxFreq = count;
res = num;
}
}

return res;
}

int main() {
vector<int> nums = {0, 1, 2, 2, 4, 4, 1};
cout << mostFrequentEven(nums) << endl; // Output: 2
return 0;
}

Complexity Analysis​

  • Time Complexity: O(n2)O(n^2)
  • due to the nested loop for counting frequency and finding the maximum.
  • Space Complexity: O(n)O(n)
  • for storing the frequency of numbers.

Video Explanation of Given Problem​


Authors:

Loading...