Leetcode 2404: Most Frequent Even Element

grid47
grid47
Exploring patterns and algorithms
Mar 11, 2024 5 min read

You are given an integer array nums. Your task is to return the most frequent even element in the array. If there is a tie (i.e., multiple even elements appear the most number of times), return the smallest one. If there is no even element, return -1.
Problem
Approach
Steps
Complexity
Input: You are given an integer array `nums` containing elements from 0 to 100,000.
Example: nums = [1, 3, 5, 2, 4, 4, 4]
Constraints:
• 1 <= nums.length <= 2000
• 0 <= nums[i] <= 10^5
Output: Return the most frequent even element in the array. If no even element exists, return -1.
Example: Output: 4
Constraints:
Goal: The goal is to find the most frequent even element, and in case of a tie, return the smallest one.
Steps:
• 1. Create a map (hash table) to count the frequency of each element in the array.
• 2. Loop through the map and identify the most frequent even element.
• 3. If there is a tie in frequency, select the smallest element.
• 4. If no even element is found, return -1.
Goal: Ensure that the solution efficiently handles arrays of sizes up to 2000 with integer elements in the range 0 to 100,000.
Steps:
• The solution should run in linear time relative to the size of the input array.
Assumptions:
• The input array is valid and consists only of non-negative integers.
Input: nums = [0, 1, 2, 2, 4, 4, 1]
Explanation: The even elements in the array are 0, 2, and 4. Both 2 and 4 appear the most times, but since 2 is smaller, it is returned.

Input: nums = [3, 5, 7, 9]
Explanation: There are no even elements in the array, so the result is -1.

Input: nums = [4, 4, 4, 9, 2, 4]
Explanation: The even element 4 appears most frequently, so it is returned.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus