Taro Logo

Average Value of Even Numbers That Are Divisible by Three

Easy
Asked by:
Profile picture
27 views
Topics:
Arrays

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 <= 1000
  • 1 <= nums[i] <= 1000

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the expected range of values for the integers in the `nums` array? Are we dealing with integers that can fit within a standard 32-bit integer, or should I anticipate larger numbers?
  2. What should I return if the input array `nums` is null or empty?
  3. Are all numbers in the `nums` array guaranteed to be positive integers as stated in the problem description, or should I handle potential edge cases such as zero or negative numbers?
  4. If the average of the numbers that are both even and divisible by three is not an integer, how should I handle the rounding? Should I truncate, round up, or round to the nearest integer?
  5. Are there any constraints on the size of the `nums` array (e.g., maximum number of elements) that I should consider?

Brute Force Solution

Approach

We need to find the average of some special numbers from a collection. The brute force method means we'll look at each number individually to see if it's special, and then do some math.

Here's how the algorithm would work step-by-step:

  1. Go through each number in the collection, one at a time.
  2. For each number, check if it is both an even number and divisible by three.
  3. If a number meets both conditions, remember it.
  4. After checking all the numbers, add up all the numbers that you remembered.
  5. Count how many numbers you remembered.
  6. Divide the sum of the remembered numbers by the count of the remembered numbers. The result is the average.

Code Implementation

def average_of_even_divisible_by_three(numbers):
    sum_of_valid_numbers = 0
    count_of_valid_numbers = 0

    for number in numbers:
        # Check if the number is even.
        if number % 2 == 0:

            # Check if the number is divisible by three.
            if number % 3 == 0:
                sum_of_valid_numbers += number
                count_of_valid_numbers += 1

    # Avoid division by zero if no numbers meet the criteria.
    if count_of_valid_numbers == 0:
        return 0

    average = sum_of_valid_numbers / count_of_valid_numbers
    return average

Big(O) Analysis

Time Complexity
O(n)The provided solution iterates through each of the 'n' numbers in the input collection once. For each number, it performs a constant amount of work: checking if the number is even and divisible by three. After the loop, it calculates the average, which takes constant time regardless of the input size. Therefore, the dominant factor is the single loop through the input, resulting in O(n) time complexity.
Space Complexity
O(1)The provided algorithm uses a constant amount of extra space. It only needs to store a sum and a count of the even numbers divisible by three. These variables do not depend on the size of the input array, N, therefore the auxiliary space complexity is O(1).

Optimal Solution

Approach

To efficiently find the average, we only consider numbers that meet both conditions: being even and divisible by three. We track only the necessary information which drastically reduces processing.

Here's how the algorithm would work step-by-step:

  1. Go through each number in the given set one by one.
  2. For each number, check if it is even. If it isn't, skip to the next number.
  3. If the number is even, check if it is also divisible by three. If it isn't, skip to the next number.
  4. If the number is both even and divisible by three, add it to a running total and increase a counter by one.
  5. After checking all the numbers, divide the running total by the counter to get the average of the numbers that met both criteria. If the counter is zero (meaning no numbers met the criteria), the average is zero.

Code Implementation

def average_value_of_even_numbers_divisible_by_three(numbers):
    sum_of_valid_numbers = 0
    count_of_valid_numbers = 0

    for number in numbers:
        # Only consider even numbers.
        if number % 2 == 0:

            # Further filter for divisibility by 3.
            if number % 3 == 0:

                # Accumulate the number and increment the count.
                sum_of_valid_numbers += number
                count_of_valid_numbers += 1

    # Avoid division by zero if no valid numbers are found.
    if count_of_valid_numbers == 0:
        return 0

    average = sum_of_valid_numbers / count_of_valid_numbers
    return average

Big(O) Analysis

Time Complexity
O(n)The algorithm iterates through each number in the input array once. For each number, it performs a constant number of operations: checking if it's even and if it's divisible by three. Since the number of operations within the loop is constant and the loop iterates n times, where n is the size of the input array, the time complexity is O(n).
Space Complexity
O(1)The algorithm uses a running total and a counter to keep track of the sum and number of even numbers divisible by three. These are constant space integer variables. The space used does not depend on the input size N (the number of elements in the given set). Therefore, the space complexity is O(1).

Edge Cases

Empty input array
How to Handle:
Return 0 immediately as there are no numbers to process.
Array contains no numbers divisible by both 2 and 3
How to Handle:
Return 0 as per the problem statement when no qualifying numbers are found.
Array contains only one element that is divisible by both 2 and 3
How to Handle:
Calculate the average (which is just the number itself) and return it as an integer.
Array contains extremely large positive integers
How to Handle:
Ensure that the sum of the qualifying numbers does not cause integer overflow; use a larger data type if necessary.
Array contains a mix of positive integers including some that are both even and divisible by three.
How to Handle:
The standard solution logic correctly filters and averages these numbers.
All numbers in the array are even and divisible by three.
How to Handle:
Calculate the average of all the numbers.
The average is not a whole number
How to Handle:
Truncate the floating-point average to an integer, according to the problem description.
Null input array
How to Handle:
Throw an IllegalArgumentException (or equivalent for the language being used) or return 0 after logging an error, depending on requirements.