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

EasyArrayMath
Problem
#2455
Reading time
2 min

The problem

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

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.

Python solution

Python
class Solution:
    def averageValue(self, nums: List[int]) -> int:
        s = n = 0
        for x in nums:
            if x % 6 == 0:
                s += x
                n += 1
        return 0 if n == 0 else s // n

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array
SpaceO(1) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2455. Average Value of Even Numbers That Are Divisible by Three is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2455. Average Value of Even Numbers That Are Divisible by Three?
LeetCode 2455. Average Value of Even Numbers That Are Divisible by Three is rated Easy on LeetCode.
What is the time complexity of LeetCode 2455. Average Value of Even Numbers That Are Divisible by Three?
The Python solution on this page runs in O(n), where n is the length of the array.
What is the space complexity of LeetCode 2455. Average Value of Even Numbers That Are Divisible by Three?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2455. Average Value of Even Numbers That Are Divisible by Three cover?
LeetCode 2455. Average Value of Even Numbers That Are Divisible by Three is tagged Array and Math on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview