algoadvance

You are given an integer array nums. Find the most frequent even element.

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

Example:

Clarifying Questions

  1. Input Constraints:
    • What is the length range of the array nums?
      • The length of nums can be from 1 to (10^5).
    • What are the value ranges for elements in nums?
      • Elements in nums can be from 0 to (10^5).
  2. Output Specifics:
    • What should be the output if there are no even numbers in the array?
      • If there are no even numbers in the array, return -1.

Strategy

  1. Filter Out Even Numbers:
    • Loop through the array nums and identify all even numbers.
  2. Count Frequencies:
    • Use a dictionary to maintain a count of all even numbers.
  3. Determine Most Frequent and Smallest:
    • Traverse the dictionary to find the most frequent even number. In case of a tie in frequency, choose the smaller number.
  4. Edge Cases:
    • If no even numbers are found, return -1.

Code

Here is the Python code implementation based on our strategy:

def most_frequent_even(nums):
    # Dictionary to store the frequency of even elements
    freq = {}
    
    # Iterate through nums and count frequencies of even numbers
    for num in nums:
        if num % 2 == 0:
            if num in freq:
                freq[num] += 1
            else:
                freq[num] = 1
    
    # No even numbers case
    if not freq:
        return -1
    
    # Determine the most frequent even number, 
    # If there's a tie, return the smallest even number.
    most_frequent = -1
    max_freq = 0
    
    for num, count in freq.items():
        if count > max_freq or (count == max_freq and num < most_frequent):
            max_freq = count
            most_frequent = num
    
    return most_frequent
    
# Example usage:
nums = [0,1,2,2,4,4,1]
print(most_frequent_even(nums))  # Output: 2

Time Complexity

Overall time complexity is O(n), which is efficient given the constraints.

Try our interview co-pilot at AlgoAdvance.com