You are given an integer array nums
. Find the most frequent even element.
-1
.Example:
nums = [0,1,2,2,4,4,1]
2
nums
?
nums
can be from 1 to (10^5).nums
?
nums
can be from 0 to (10^5).-1
.nums
and identify all even numbers.-1
.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
nums
.Overall time complexity is O(n), which is efficient given the constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?