File: average-value-of-even-numbers-that-are-divisible-by-three/solution.py

Date: 2026-06-06

Time: 15:19

Purpose

This file solves LeetCode 2455: Average Value of Even Numbers That Are Divisible by Three. It owns exactly one responsibility: given a list of positive integers, compute the floor-average of elements that are both even and divisible by 3, returning 0 if no such elements exist.

Key Components

averageevendivisiblebythree(nums: list[int]) -> int

The sole exported function. Contract:

Patterns

The n % 6 == 0 collapse. The problem title says "even numbers divisible by three," which means n % 2 == 0 and n % 3 == 0. The solution collapses both checks into n % 6 == 0 — since lcm(2, 3) = 6, a number is divisible by both 2 and 3 if and only if it's divisible by 6. This is a standard number-theory simplification seen across many solutions in this repo.

Single-pass accumulation. Instead of filtering into a list and then computing the average (which would allocate O(k) memory for qualifying elements), the code accumulates total and count in a single pass. This is O(1) auxiliary space, O(n) time.

Integer division via //. The problem specifies rounding down, which Python's // operator handles correctly for non-negative values.

Dependencies

Flow

1. Initialize total and count to 0.

2. Iterate over every element n in nums.

3. If n % 6 == 0, add n to total and increment count.

4. After the loop, return total // count if count > 0, else 0.

No early exits, no branching beyond the single modulo check.

Invariants

Error Handling

There is none — and intentionally so. This is a LeetCode solution operating under the problem's guarantees (1 <= nums.length <= 1000, 1 <= nums[i] <= 1000). The function trusts its caller to provide a non-empty list of positive integers. Empty lists produce 0 (the fallback), but no explicit validation or exception raising exists.

Topics to Explore

Beliefs