You are given an integer array nums. You need to return the average value of the even numbers that are divisible by three. If there are no such numbers, return 0.
For the sake of this solution, I will assume:
The algorithm consists of a single pass through the array to filter valid numbers and another step to compute the average. The time complexity is O(N), where N is the number of elements in the input array.
def averageValueOfEvenNumbersDivisibleByThree(nums):
# Filter even numbers that are also divisible by three
valid_nums = [num for num in nums if num % 2 == 0 and num % 3 == 0]
# If there are no valid numbers, return 0
if not valid_nums:
return 0.0
# Calculate the average of the valid numbers
average = sum(valid_nums) / len(valid_nums)
return average
# Example usage:
nums = [1, 6, 9, 12, 15, 18]
print(averageValueOfEvenNumbersDivisibleByThree(nums)) # Output: 12.0
num % 2 == 0 ensures the number is even.num % 3 == 0 ensures the even number is also divisible by 3.valid_nums is empty, return 0.0.sum(valid_nums) / len(valid_nums) and return the result.This approach ensures the solution is efficient and simple.
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?