Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/2404.html

2404. Most Frequent Even Element

  • Difficulty: Easy.
  • Related Topics: .
  • Similar Questions: Majority Element, Majority Element II, Top K Frequent Elements, Sort Characters By Frequency.

Problem

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.

  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 (Java, C++, Python)

  • class Solution {
        public int mostFrequentEven(int[] A) {
            HashMap<Integer,Integer> mp= new HashMap<>();
            int val=1000000,freq=0;
            for(var i:A){
                //if even element
                if(i%2==0){
                    //increase frequency in map
                    int curr= mp.getOrDefault(i,0)+1;
                    mp.put(i,curr);
                    //Update smallest with greatest frequency
                    if(curr>freq || curr==freq && i<val){
                        val=i;
                        freq=curr;
                    }
                }
            }
            return freq==0? -1 : val;
        }
    }
    
    ############
    
    class Solution {
        public int mostFrequentEven(int[] nums) {
            Map<Integer, Integer> cnt = new HashMap<>();
            for (int v : nums) {
                if (v % 2 == 0) {
                    cnt.put(v, cnt.getOrDefault(v, 0) + 1);
                }
            }
            int ans = -1, mx = 0;
            for (var e : cnt.entrySet()) {
                int v = e.getKey(), t = e.getValue();
                if (mx < t || (mx == t && ans > v)) {
                    mx = t;
                    ans = v;
                }
            }
            return ans;
        }
    }
    
  • class Solution:
        def mostFrequentEven(self, nums: List[int]) -> int:
            cnt = Counter(v for v in nums if v % 2 == 0)
            ans, mx = -1, 0
            for v, t in cnt.items():
                if mx < t or (mx == t and ans > v):
                    mx = t
                    ans = v
            return ans
    
    ############
    
    # 2404. Most Frequent Even Element
    # https://leetcode.com/problems/most-frequent-even-element/
    
    class Solution:
        def mostFrequentEven(self, nums: List[int]) -> int:
            counter = Counter()
            have = False
            
            for x in nums:
                if x % 2 == 0:
                    counter[x] += 1
                    have = True
            
            if not have: return -1
            
            mmax = max(counter.values())
            
            for x in sorted(counter.keys()):
                if counter[x] == mmax:
                    return x
            
            return -1
    
    
  • class Solution {
    public:
        int mostFrequentEven(vector<int>& nums) {
            unordered_map<int, int> cnt;
            for (int v : nums) {
                if (v % 2 == 0) {
                    ++cnt[v];
                }
            }
            int ans = -1, mx = 0;
            for (auto [v, t] : cnt) {
                if (mx < t || (mx == t && ans > v)) {
                    mx = t;
                    ans = v;
                }
            }
            return ans;
        }
    };
    
  • func mostFrequentEven(nums []int) int {
    	cnt := map[int]int{}
    	for _, v := range nums {
    		if v%2 == 0 {
    			cnt[v]++
    		}
    	}
    	ans, mx := -1, 0
    	for v, t := range cnt {
    		if mx < t || (mx == t && ans > v) {
    			mx = t
    			ans = v
    		}
    	}
    	return ans
    }
    
  • function mostFrequentEven(nums: number[]): number {
        const map = new Map();
        for (const num of nums) {
            if (num % 2 === 0) {
                map.set(num, (map.get(num) ?? 0) + 1);
            }
        }
        if (map.size === 0) {
            return -1;
        }
    
        let res = 0;
        let max = 0;
        for (const [k, v] of map.entries()) {
            if (v > max || (v == max && k < res)) {
                max = v;
                res = k;
            }
        }
        return res;
    }
    
    
  • use std::collections::HashMap;
    impl Solution {
        pub fn most_frequent_even(nums: Vec<i32>) -> i32 {
            let mut map = HashMap::new();
            for &num in nums.iter() {
                if num % 2 == 0 {
                    *map.entry(num).or_insert(0) += 1;
                }
            }
            if map.len() == 0 {
                return -1;
            }
    
            let mut res = 0;
            let mut max = 0;
            for (&k, &v) in map.iter() {
                if v > max || (v == max && k < res) {
                    max = v;
                    res = k;
                }
            }
            res
        }
    }
    
    
  • class Solution {
        /**
         * @param Integer[] $nums
         * @return Integer
         */
        function mostFrequentEven($nums) {
            $max = $rs = -1;
            for ($i = 0; $i < count($nums); $i++) {
                if ($nums[$i] % 2 == 0) {
                    $hashtable[$nums[$i]] += 1;
                    if ($hashtable[$nums[$i]] > $max || ($hashtable[$nums[$i]] == $max && $rs > $nums[$i])) {
                        $max = $hashtable[$nums[$i]];
                        $rs = $nums[$i];
                    }
                }
            }
            return $rs;
        }
    }
    

Explain:

nope.

Complexity:

  • Time complexity : O(n).
  • Space complexity : O(n).

All Problems

All Solutions