Average Value of Even Numbers That Are Divisible by Three solution and explanation
9 more videos on this problem
2455. Average Value of Even Numbers That Are Divisible by Three | Weekly Contest 317 | LeetCode 2455Bro Coders · 1:58 · 531 views
2455. Average Value of Even Numbers That Are Divisible by Three | LEETCODE EASYcode Explainer · 2:41 · 277 views
Leetcode 2455: Average Value of Even Numbers That Are Divisible by ThreeAlgorithms Casts · 2:42 · 258 views
Average Value of Even Numbers That Are Divisible by Three || 2455 || Leetcode Contest Easy || MathCoding Techniques with Komal | Newton School · 6:51 · 232 views
2455. Average Value of Even Numbers That Are Divisible by Three (Leetcode Easy)Programming Live with Larry · 2:30 · 202 views
Leetcode Weekly contest 317 - Easy - Average Value of Even Numbers That Are Divisible by ThreePrakhar Agrawal · 2:08 · 143 views
2455. Average Value of Even Numbers That Are Divisible by Three with Python | Best ExplanationArsalan Ahmed · 5:45 · 71 views
Leetcode 2455. Average Value of Even Numbers That Are Divisible by Three [Solution]Elite Code · 4:26 · 66 views
2455. Average Value of Even Numbers That Are Divisible by ThreeDeep Coding · 2:49 · 66 views
Leetcode Weekly Contest 317 | Average Value of Even Numbers That Are Divisible by Three | EasyCoding with Jenish · 1:04 · 58 views
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 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 <= 10001 <= nums[i] <= 1000
Approach overview
Problem Overview: Given an integer array, compute the average of values that are both even and divisible by three. If no such numbers exist, return 0. The task reduces to filtering numbers divisible by 6, tracking their sum and count, then returning sum / count.
Approach 1: Recursive Approach with Memoization (O(n) time, O(n) space)
This approach processes the array using recursion. At each index, check whether the current value is divisible by 6. If it is, update the running sum and count. The recursive function moves to the next index until the end of the array. Memoization stores intermediate states such as (index) to avoid recomputation if the recursion revisits the same position.
The key idea is breaking the problem into smaller subproblems: compute the valid sum and count from the remaining suffix of the array. After recursion finishes, calculate the average using the aggregated values. Time complexity is O(n) since each element is processed once, while recursion and memo storage require O(n) space. This method demonstrates recursive problem decomposition on array traversal.
Approach 2: Iterative Dynamic Programming Approach (O(n) time, O(1) space)
The optimal solution uses a single pass through the array. Maintain two variables: sum for the total of qualifying numbers and count for how many satisfy the condition. During iteration, check num % 6 == 0. This works because a number divisible by both 2 and 3 must be divisible by 6.
Each valid number updates sum += num and count++. After finishing the loop, return sum / count if count > 0; otherwise return 0. This approach leverages basic properties of math and linear scanning of an array. Since only two variables are maintained, space complexity remains constant at O(1) while time complexity is O(n).
Recommended for interviews: The iterative single-pass solution is what interviewers expect. It demonstrates that you recognize the mathematical shortcut (divisible by 6) and can compute aggregates in one traversal. Mentioning the recursive variant shows understanding of alternative traversal strategies, but the constant-space iterative approach is the most practical and efficient.
Approach 1: Recursive Approach with Memoization
This approach uses recursion to solve the problem by breaking it down into smaller subproblems. To optimize, we use memoization to store the results of already solved sub-problems, thus avoiding redundant calculations.
def fibonacci(n, memo=None):
if memo is None:
memo = [-1] * 1000
if n <= 1:
return n
if memo[n] != -1:
return memo[n]
memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo)
return memo[n]
print(fibonacci(10)) # Example usageimport java.util.Arrays;
public class Fibonacci {
private static int[] memo = new int[1000];
public static int fibonacci(int n) {
if (n <= 1) return n;
if (memo[n] != -1) return memo[n];
memo[n] = fibonacci(n - 1) + fibonacci(n - 2);
return memo[n];
}
public static void main(String[] args) {
Arrays.fill(memo, -1);
System.out.println(fibonacci(10)); // Example usage
}
}#include <iostream>
#include <vector>
std::vector<int> memo(1000, -1);
int fibonacci(int n) {
if (n <= 1) return n;
if (memo[n] != -1) return memo[n];
memo[n] = fibonacci(n - 1) + fibonacci(n - 2);
return memo[n];
}
int main() {
std::cout << fibonacci(10) << std::endl;
return 0;
}function fibonacci(n, memo = []) {
if (n <= 1) return n;
if (memo[n] !== undefined) return memo[n];
memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo);
return memo[n];
}
console.log(fibonacci(10)); // Example usage#include <stdio.h>
#include <string.h>
#define MAX 1000
int memo[MAX];
int fibonacci(int n) {
if (n <= 1) return n;
if (memo[n] != -1) return memo[n];
memo[n] = fibonacci(n-1) + fibonacci(n-2);
return memo[n];
}
int main() {
memset(memo, -1, sizeof(memo));
printf("%d\n", fibonacci(10)); // Example usage
return 0;
}using System;
class Program {
static int[] memo = new int[1000];
static int Fibonacci(int n) {
if (n <= 1) return n;
if (memo[n] != -1) return memo[n];
memo[n] = Fibonacci(n - 1) + Fibonacci(n - 2);
return memo[n];
}
static void Main() {
Array.Fill(memo, -1);
Console.WriteLine(Fibonacci(10)); // Example usage
}
}This Python solution defines a `fibonacci` function that uses a default argument `memo` to store results of previous computations. Using memoization, it reduces redundant calculations.
Time Complexity: O(n)
Space Complexity: O(n) because of memo array.
Approach 2: Iterative Dynamic Programming Approach
This approach utilizes dynamic programming to solve the problem iteratively. We construct a table to store results of subproblems and use these results to solve the problem iteratively while minimizing space usage.
def fibonacci(n):
if n <= 1:
return n
fib = [0, 1] + [0] * (n - 1)
for i in range(2, n + 1):
fib[i] = fib[i - 1] + fib[i - 2]
return fib[n]
print(fibonacci(10)) # Example usagepublic class Fibonacci {
public static int fibonacci(int n) {
if (n <= 1) return n;
int[] fib = new int[n + 1];
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i <= n; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
return fib[n];
}
public static void main(String[] args) {
System.out.println(fibonacci(10)); // Example usage
}
}#include <iostream>
int fibonacci(int n) {
if (n <= 1) return n;
int fib[n+1];
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i <= n; i++) {
fib[i] = fib[i-1] + fib[i-2];
}
return fib[n];
}
int main() {
std::cout << fibonacci(10) << std::endl;
return 0;
}function fibonacci(n) {
if (n <= 1) return n;
let fib = new Array(n + 1).fill(0);
fib[1] = 1;
for (let i = 2; i <= n; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
return fib[n];
}
console.log(fibonacci(10)); // Example usage#include <stdio.h>
int fibonacci(int n) {
if (n <= 1) return n;
int fib[n+1];
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i <= n; i++) {
fib[i] = fib[i-1] + fib[i-2];
}
return fib[n];
}
int main() {
printf("%d\n", fibonacci(10)); // Example usage
return 0;
}using System;
class Program {
static int Fibonacci(int n) {
if (n <= 1) return n;
int[] fib = new int[n + 1];
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i <= n; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
return fib[n];
}
static void Main() {
Console.WriteLine(Fibonacci(10)); // Example usage
}
}This Python solution employs an array to store Fibonacci numbers iteratively. The function uses the relationship F(i) = F(i-1) + F(i-2) to fill the array up to the required position.
Time Complexity: O(n)
Space Complexity: O(n)
Approach 3: Simulation
We notice that an even number divisible by 3 must be a multiple of 6. Therefore, we only need to traverse the array, count the sum and the number of all multiples of 6, and then calculate the average.
The time complexity is O(n), where n is the length of the array. The space complexity is O(1).
function averageValue(nums: number[]): number {
let s = 0;
let n = 0;
for (const x of nums) {
if (x % 6 === 0) {
s += x;
++n;
}
}
return n === 0 ? 0 : ~~(s / n);
}func averageValue(nums []int) int {
var s, n int
for _, x := range nums {
if x%6 == 0 {
s += x
n++
}
}
if n == 0 {
return 0
}
return s / n
}impl Solution {
pub fn average_value(nums: Vec<i32>) -> i32 {
let mut s = 0;
let mut n = 0;
for x in nums.iter() {
if x % 6 == 0 {
s += x;
n += 1;
}
}
if n == 0 {
return 0;
}
s / n
}
}Approach 4: Default Approach
impl Solution {
pub fn average_value(nums: Vec<i32>) -> i32 {
let filtered_nums: Vec<i32> = nums.iter().cloned().filter(|&n| n % 6 == 0).collect();
if filtered_nums.is_empty() {
return 0;
}
filtered_nums.iter().sum::<i32>() / (filtered_nums.len() as i32)
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Recursive Approach with Memoization | Time Complexity: O(n) |
| Iterative Dynamic Programming Approach | Time Complexity: O(n) |
| Simulation | – |
| Default Approach | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Recursive Approach with Memoization | O(n) | O(n) | Useful for practicing recursive array traversal or when extending the problem to more complex state tracking |
| Iterative Dynamic Programming (Single Pass) | O(n) | O(1) | Best general solution; minimal memory and fastest implementation for scanning arrays |
Frequently asked questions
Is Average Value of Even Numbers That Are Divisible by Three easy or hard?
Average Value of Even Numbers That Are Divisible by Three is classified as an Easy problem. It focuses on basic array traversal, simple divisibility checks, and maintaining running totals, making it suitable for beginners practicing array and math fundamentals.
Average Value of Even Numbers That Are Divisible by Three Python/Java solution
In Python or Java, iterate through the array and check num % 6 == 0. Maintain sum and count variables, update them for each valid element, and return sum // count (or sum / count depending on language rules) if count is non-zero; otherwise return 0.
How to solve Average Value of Even Numbers That Are Divisible by Three in O(n)?
Iterate through the array once and check if each element satisfies num % 6 == 0. If it does, add it to a running sum and increment a counter. After the loop, return sum / count if count is greater than zero; otherwise return 0.
What is the best approach for Average Value of Even Numbers That Are Divisible by Three?
The best approach is a single-pass iteration over the array. Track the sum and count of numbers divisible by 6, since divisibility by both 2 and 3 implies divisibility by 6. This solution runs in O(n) time and O(1) space and is typically expected in interviews.
Is Average Value of Even Numbers That Are Divisible by Three asked at Google/Amazon/Meta?
This exact problem may appear on practice platforms like LeetCode as an easy-level exercise. Variations involving filtering arrays and computing aggregates are common in coding screens at companies like Amazon and Google because they test basic array traversal and condition checks.
What data structure is used in Average Value of Even Numbers That Are Divisible by Three?
The problem primarily uses an array as the input data structure. The algorithm performs a linear scan over the array and maintains simple scalar variables for sum and count, without requiring additional data structures.
What is the time complexity of Average Value of Even Numbers That Are Divisible by Three?
The optimal solution runs in O(n) time where n is the length of the array. Each element is checked once for the condition num % 6 == 0. Space complexity is O(1) because only two variables (sum and count) are maintained.
