We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Most Frequent Even Element

Number: 2486

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given an integer array nums, return the most frequent even element. If there is a tie, return the smallest even element. If no even element exists, return -1.


Key Insights

  • Use a hash table to count the frequency of even numbers.
  • Ignore odd numbers during the counting process.
  • Determine the most frequent even number; in the case of a tie, select the smallest even number.
  • Return -1 if no even number is found.

Space and Time Complexity

Time Complexity: O(n), where n is the number of elements in the array. Space Complexity: O(n), for storing the count of even numbers in the worst case.


Solution

The solution iterates through the array once to count the occurrences of each even number using a hash table (or dictionary). After counting, it iterates over the hash table to find the even number with the highest frequency. If multiple even numbers have the same frequency, the smallest one is chosen. If no even number is encountered, the solution returns -1.


Code Solutions

# Function to find the most frequent even element
def most_frequent_even(nums):
    # Dictionary to store frequency of even numbers
    even_counts = {}
    
    # Iterate over each number in the input list
    for num in nums:
        # Check if the number is even
        if num % 2 == 0:
            # Update the count for the even number
            if num in even_counts:
                even_counts[num] += 1
            else:
                even_counts[num] = 1
                
    # If no even number is found, return -1
    if not even_counts:
        return -1
    
    # Initialize variables to track maximum frequency and candidate number
    most_frequent = -1
    max_frequency = 0
    
    # Iterate over the dictionary items
    for num, count in even_counts.items():
        # If a higher frequency is found or frequency is equal but number is smaller, update candidate
        if count > max_frequency or (count == max_frequency and num < most_frequent):
            max_frequency = count
            most_frequent = num
            
    return most_frequent

# Example usage:
print(most_frequent_even([0,1,2,2,4,4,1]))  # Expected output: 2
← Back to All Questions