algoadvance

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

Problem Statement

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

Clarifying Questions

  1. Q: What should the function return if the array is empty?
    • A: The function should return 0 since there are no integers to consider.
  2. Q: What if there are no even integers in the array?
    • A: The function should return 0 if there are no even integers divisible by 3.
  3. Q: How should the average be calculated and returned considering integer arithmetic?
    • A: The average should be calculated as a floating-point value, but since we are dealing with array elements which are integers, we can use integer division for this specific problem.

Strategy

  1. Iterate through the array: Iterate over each element in the array and check if it is both even and divisible by 3.
  2. Sum and Count: Maintain a sum variable to accumulate the qualifying values and a count variable to keep track of the number of such values.
  3. Calculate average: After processing all elements, calculate the average if the count is greater than 0; otherwise, return 0.

Code

#include <vector>
using namespace std;

class Solution {
public:
    int averageValue(vector<int>& nums) {
        int sum = 0;
        int count = 0;
        
        for (int num : nums) {
            if (num % 6 == 0) {
                sum += num;
                count++;
            }
        }
        
        return count > 0 ? sum / count : 0;
    }
};

Explanation

  1. Initialization: We start by initializing sum to 0 and count to 0.
  2. Loop Through Numbers: We loop through each number in the array:
    • Check if the number is divisible by both 2 and 3 which is equivalent to checking num % 6 == 0.
    • If the condition is satisfied, add the number to sum and increment count.
  3. Calculate Average: After the loop, if count is greater than 0, we return the integer division result of sum divided by count. Otherwise, we return 0.

Time Complexity

This solution is efficient and concise, adhering to the requirements of the problem.

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