We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Average Value of Even Numbers That Are Divisible by Three

Number: 2542

Difficulty: Easy

Paid? No

Companies: Accenture, IBM


Problem Description

Given an array of positive integers, return the average (rounded down) of all even numbers that are divisible by 3. If no such numbers exist, return 0.


Key Insights

  • Filter numbers that are both even and divisible by 3.
  • Maintain a running sum and count of the valid numbers.
  • Use floor division (or equivalent) to return the average.
  • If count is zero (i.e., no valid numbers), output 0.

Space and Time Complexity

Time Complexity: O(n), where n is the number of elements in the array. Space Complexity: O(1), since only a fixed number of extra variables are used.


Solution

The approach involves iterating through the array once while checking if each number is even and also divisible by 3. If it is, add it to a sum and increment a count. After the loop, if count is greater than zero, return the floor of (sum / count); otherwise, return 0. The algorithm makes use of simple arithmetic checks and maintains constant extra space.


Code Solutions

def averageValue(nums):
    total_sum = 0
    count = 0
    # Iterate over each number in the list
    for num in nums:
        # Check if the number is even and divisible by 3
        if num % 2 == 0 and num % 3 == 0:
            total_sum += num  # Add valid number to the total sum
            count += 1        # Increment count of valid numbers
    # If no valid numbers are found, return 0; otherwise, compute the floor of the average
    return total_sum // count if count > 0 else 0

# Example usage:
print(averageValue([1, 3, 6, 10, 12, 15]))  # Output: 9
← Back to All Questions