algoadvance

Leetcode 2455. Average Value of Even Numbers That Are Divisible by Three

Problem Statement

Given an integer array nums of positive integers, calculate and return the average of all even numbers that are divisible by 3. If there are no such numbers, return 0.

Clarifying Questions

  1. Input constraints: What is the maximum length of the input array?
    • The array can have up to 10^4 integers.
  2. Input values: Are all input values guaranteed to be positive integers?
    • Yes, all values will be positive integers.
  3. Return type: Should the function return an integer or a float for the average value?
    • The function should return an integer. We’ll take the floor value of the average if it’s not a whole number.
  4. Edge cases: What should be returned if there are no even numbers divisible by 3?
    • If there are no such numbers, the function should return 0.

Strategy

  1. Iteration: Iterate through the array and check each number.
  2. Conditions: Determine if a number is both even and divisible by 3.
  3. Accumulation: Accumulate the sum of these qualifying numbers and count them.
  4. Calculation: Calculate the average based on the sum and count.
  5. Return: Return the integer part of the calculated average or 0 if no qualifying numbers are found.

Code

public class Solution {
    public int averageValue(int[] nums) {
        int sum = 0;
        int count = 0;

        for (int num : nums) {
            if (num % 2 == 0 && num % 3 == 0) {
                sum += num;
                count++;
            }
        }

        // If no even numbers that are divisible by 3 are found
        if (count == 0) {
            return 0;
        }

        // Calculate and return the average (floor division)
        return sum / count;
    }
}

Time Complexity

This approach ensures that we efficiently compute the desired average with a guaranteed linear time complexity.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI