Average Value of Even Numbers That Are Divisible by Three Problem
#2455
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2455.
Given an integer array nums of positive integers, return the average value of all even integers that are divisible by 3.
Note that the average of n elements is the sum of the n elements divided by n and rounded down to the nearest integer.
Example 1:
Input: nums = [1,3,6,10,12,15]
Output: 9
Explanation: 6 and 12 are even numbers that are divisible by 3. (6 + 12) / 2 = 9.
Example 2:
Input: nums = [1,2,4,7,10]
Output: 0
Explanation: There is no single number that satisfies the requirement, so return 0.
Constraints:
1 <= nums.length <= 10001 <= nums[i] <= 1000
Solution
Approach: Simulation
An even number divisible by 3 is a multiple of 6. Go through the array, sum the multiples of 6 and count them, then return the sum divided by the count, rounded down (or 0 if there are none).
Complexity: O(n) time and O(1) space.
class Solution:
def averageValue(self, nums: List[int]) -> int:
s = n = 0
for x in nums:
if x % 6 == 0:
s += x
n += 1
return 0 if n == 0 else s // n