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

In this guide, you will get 2455. Average Value of Even Numbers That Are Divisible by Three LeetCode Solution with the best time and space complexity. The solution to Average Value of Even Numbers That Are Divisible by Three problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Average Value of Even Numbers That Are Divisible by Three solution in C++
  4. Average Value of Even Numbers That Are Divisible by Three solution in Java
  5. Average Value of Even Numbers That Are Divisible by Three solution in Python
  6. Additional Resources
2455. Average Value of Even Numbers That Are Divisible by Three LeetCode Solution image

Problem Statement of Average Value of Even Numbers That Are Divisible by Three

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

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

2455. Average Value of Even Numbers That Are Divisible by Three LeetCode Solution in C++

class Solution {
 public:
  int averageValue(vector<int>& nums) {
    int sum = 0;
    int count = 0;

    for (const int num : nums)
      if (num % 6 == 0) {
        sum += num;
        ++count;
      }

    return count == 0 ? 0 : sum / count;
  }
};
/* code provided by PROGIEZ */

2455. Average Value of Even Numbers That Are Divisible by Three LeetCode Solution in Java

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

    for (final int num : nums)
      if (num % 6 == 0) {
        sum += num;
        ++count;
      }

    return count == 0 ? 0 : sum / count;
  }
}
// code provided by PROGIEZ

2455. Average Value of Even Numbers That Are Divisible by Three LeetCode Solution in Python

class Solution:
  def averageValue(self, nums: list[int]) -> int:
    summ = 0
    count = 0

    for num in nums:
      if num % 6 == 0:
        summ += num
        count += 1

    return 0 if count == 0 else summ // count
# code by PROGIEZ

Additional Resources

See also  95. Unique Binary Search Trees II LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.