Difficulty: Easy | Acceptance: 63.20% | Paid: No Topics: Array, Math
Given an integer array nums, return the average value of all even numbers that are divisible by three.
The average value is the integer division of the sum of the elements by the number of elements.
Note that the average of 0 elements is considered to be 0.
- Examples
- Constraints
- Iterative Single Pass
- Functional Approach
Examples
Example 1:
Input: nums = [1,3,6,10,12]
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 are no even numbers that are divisible by 3 in the given array.
Constraints
1 <= nums.length <= 1000
1 <= nums[i] <= 1000
Iterative Single Pass
Intuition We iterate through the array once, checking if each number satisfies the condition of being divisible by both 2 and 3 (which is equivalent to being divisible by 6). We accumulate the sum and count of these valid numbers to compute the average.
Steps
- Initialize
total_sumto 0 andcountto 0. - Loop through each number in the input array.
- If the number is divisible by 6, add it to
total_sumand incrementcount. - After the loop, if
countis 0, return 0. Otherwise, returntotal_sum / count.
class Solution:
def averageValue(self, nums: List[int]) -> int:
total_sum = 0
count = 0
for num in nums:
if num % 6 == 0:
total_sum += num
count += 1
return total_sum // count if count > 0 else 0
Complexity
- Time: O(n), where n is the number of elements in the array.
- Space: O(1), as we only use a few variables for storage.
- Notes: This is the most efficient approach in terms of both time and space complexity.
Functional Approach
Intuition
We utilize functional programming constructs like filter and reduce (or streams) to declaratively process the array. We first filter the numbers that are divisible by 6, then calculate the sum and count of the filtered list.
Steps
- Filter the array to keep only numbers divisible by 6.
- Calculate the sum of the filtered numbers.
- Determine the count of the filtered numbers.
- Return the integer division of the sum by the count, or 0 if the count is 0.
class Solution:
def averageValue(self, nums: List[int]) -> int:
filtered = [x for x in nums if x % 6 == 0]
return sum(filtered) // len(filtered) if filtered else 0
Complexity
- Time: O(n), as we must traverse the array to filter and reduce.
- Space: O(n) in the worst case (if all elements are valid), as functional methods often create intermediate arrays or objects.
- Notes: While concise, this approach may use more memory than the iterative approach due to intermediate collections.