2455. Average Value of Even Numbers That Are Divisible by Three
Problem Description
You are given an array nums
containing positive integers. Your task is to find the average value of all numbers in the array that are both even AND divisible by 3.
To calculate the average:
- Find all numbers that satisfy both conditions (even and divisible by 3)
- Sum these numbers together
- Divide the sum by the count of these numbers
- Round down the result to the nearest integer
If no numbers satisfy both conditions, return 0.
The key insight is that a number that is both even (divisible by 2) and divisible by 3 must be divisible by 6. This is because for a number to be divisible by both 2 and 3, it must be divisible by their least common multiple, which is 6.
For example:
- If
nums = [1, 3, 6, 10, 12, 15]
, the numbers that are both even and divisible by 3 are[6, 12]
- Their sum is
6 + 12 = 18
- Their count is
2
- The average is
18 / 2 = 9
The solution iterates through the array, checks if each number is divisible by 6 (using x % 6 == 0
), accumulates the sum and count of such numbers, and finally returns the integer division of sum by count. If no valid numbers are found, it returns 0.
Intuition
The first observation is understanding what numbers we're looking for. We need numbers that are:
- Even (divisible by 2)
- Divisible by 3
When a number must be divisible by two different values, we need to think about their relationship. A number that's divisible by both 2 and 3 must be divisible by their least common multiple (LCM). Since 2 and 3 are coprime (they share no common factors other than 1), their LCM is simply 2 × 3 = 6
.
This means instead of checking two conditions separately:
if x % 2 == 0 and x % 3 == 0
We can simplify to a single condition:
if x % 6 == 0
This optimization makes the solution cleaner and more efficient.
Once we identify which numbers to include, calculating the average becomes straightforward:
- Keep a running sum of all numbers divisible by 6
- Count how many such numbers we find
- Divide the sum by the count (using integer division
//
since we need to round down)
The edge case to handle is when no numbers satisfy our condition. In this case, we'd have a count of 0, which would cause division by zero. The problem implicitly tells us to return 0 in this scenario (when there are no valid numbers to average).
Learn more about Math patterns.
Solution Approach
The implementation uses a simple simulation approach with two tracking variables:
-
Initialize counters: We start with two variables:
s = 0
: to accumulate the sum of valid numbersn = 0
: to count how many valid numbers we find
-
Iterate through the array: We traverse each element
x
innums
:for x in nums:
-
Check divisibility by 6: For each number, we check if it's divisible by 6:
if x % 6 == 0:
As established earlier, checking
x % 6 == 0
is equivalent to checking if the number is both even and divisible by 3. -
Update counters: When we find a valid number:
- Add it to our sum:
s += x
- Increment our count:
n += 1
- Add it to our sum:
-
Calculate and return the average: After processing all numbers:
return 0 if n == 0 else s // n
- If
n == 0
(no valid numbers found), we return 0 - Otherwise, we return
s // n
(integer division for rounding down)
- If
The algorithm has:
- Time Complexity:
O(n)
where n is the length of the array, as we traverse it once - Space Complexity:
O(1)
as we only use two extra variables regardless of input size
This straightforward approach efficiently solves the problem without needing any complex data structures or algorithms.
Ready to land your dream job?
Unlock your dream job with a 5-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through the solution with nums = [4, 6, 9, 12, 18, 21, 24]
.
Step 1: Initialize tracking variables
s = 0
(sum of valid numbers)n = 0
(count of valid numbers)
Step 2: Process each number
-
x = 4
: Check4 % 6 == 0
? →4 % 6 = 4
→ No, skips = 0
,n = 0
-
x = 6
: Check6 % 6 == 0
? →6 % 6 = 0
→ Yes!- Add to sum:
s = 0 + 6 = 6
- Increment count:
n = 0 + 1 = 1
- Add to sum:
-
x = 9
: Check9 % 6 == 0
? →9 % 6 = 3
→ No, skips = 6
,n = 1
-
x = 12
: Check12 % 6 == 0
? →12 % 6 = 0
→ Yes!- Add to sum:
s = 6 + 12 = 18
- Increment count:
n = 1 + 1 = 2
- Add to sum:
-
x = 18
: Check18 % 6 == 0
? →18 % 6 = 0
→ Yes!- Add to sum:
s = 18 + 18 = 36
- Increment count:
n = 2 + 1 = 3
- Add to sum:
-
x = 21
: Check21 % 6 == 0
? →21 % 6 = 3
→ No, skips = 36
,n = 3
-
x = 24
: Check24 % 6 == 0
? →24 % 6 = 0
→ Yes!- Add to sum:
s = 36 + 24 = 60
- Increment count:
n = 3 + 1 = 4
- Add to sum:
Step 3: Calculate the average
- Valid numbers found:
[6, 12, 18, 24]
- Sum:
s = 60
- Count:
n = 4
- Since
n ≠ 0
, calculate average:60 // 4 = 15
Result: 15
Note how numbers like 4 (even but not divisible by 3) and 9 (divisible by 3 but not even) are correctly excluded, while only numbers divisible by 6 are included in our calculation.
Solution Implementation
1class Solution:
2 def averageValue(self, nums: List[int]) -> int:
3 # Initialize sum and count for numbers divisible by 6
4 total_sum = 0
5 count = 0
6
7 # Iterate through each number in the array
8 for num in nums:
9 # Check if the number is divisible by both 2 and 3 (i.e., divisible by 6)
10 if num % 6 == 0:
11 total_sum += num
12 count += 1
13
14 # Return 0 if no numbers are divisible by 6, otherwise return the integer average
15 return 0 if count == 0 else total_sum // count
16
1class Solution {
2 /**
3 * Calculates the average value of all elements in the array that are divisible by 6.
4 * Returns 0 if no such elements exist.
5 *
6 * @param nums the input array of integers
7 * @return the average of elements divisible by 6, or 0 if none exist
8 */
9 public int averageValue(int[] nums) {
10 int sum = 0; // Sum of elements divisible by 6
11 int count = 0; // Count of elements divisible by 6
12
13 // Iterate through each element in the array
14 for (int number : nums) {
15 // Check if the current element is divisible by 6
16 if (number % 6 == 0) {
17 sum += number; // Add to sum
18 count++; // Increment count
19 }
20 }
21
22 // Return 0 if no elements are divisible by 6, otherwise return the average
23 return count == 0 ? 0 : sum / count;
24 }
25}
26
1class Solution {
2public:
3 int averageValue(vector<int>& nums) {
4 int sum = 0; // Sum of numbers divisible by 6
5 int count = 0; // Count of numbers divisible by 6
6
7 // Iterate through all numbers in the array
8 for (int num : nums) {
9 // Check if the number is divisible by both 2 and 3 (i.e., divisible by 6)
10 if (num % 6 == 0) {
11 sum += num; // Add to sum
12 ++count; // Increment count
13 }
14 }
15
16 // Return 0 if no numbers found, otherwise return the average
17 return count == 0 ? 0 : sum / count;
18 }
19};
20
1/**
2 * Calculates the average value of all integers in the array that are divisible by 6
3 * @param nums - Array of integers to process
4 * @returns The floor of the average of numbers divisible by 6, or 0 if no such numbers exist
5 */
6function averageValue(nums: number[]): number {
7 // Sum of all numbers divisible by 6
8 let sum: number = 0;
9
10 // Count of numbers divisible by 6
11 let count: number = 0;
12
13 // Iterate through each number in the array
14 for (const num of nums) {
15 // Check if the current number is divisible by both 2 and 3 (i.e., divisible by 6)
16 if (num % 6 === 0) {
17 sum += num;
18 count++;
19 }
20 }
21
22 // Return 0 if no numbers are divisible by 6, otherwise return the floor of the average
23 // The ~~ operator is a bitwise double NOT, used here to truncate the decimal (floor for positive numbers)
24 return count === 0 ? 0 : Math.floor(sum / count);
25}
26
Time and Space Complexity
The time complexity is O(n)
, where n
is the length of the array nums
. This is because the algorithm iterates through the array exactly once, performing constant-time operations (modulo check, addition, and increment) for each element.
The space complexity is O(1)
. The algorithm only uses a fixed amount of extra space for the variables s
(sum) and n
(count), regardless of the input size. No additional data structures that grow with the input are created.
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Checking Conditions Separately Instead of Using Divisibility by 6
Pitfall: A common mistake is to check the two conditions separately:
if num % 2 == 0 and num % 3 == 0: # Less efficient
While this works correctly, it performs two modulo operations for each number instead of one. Since a number divisible by both 2 and 3 must be divisible by 6, we can optimize this.
Solution: Use a single check for divisibility by 6:
if num % 6 == 0: # More efficient
2. Using Regular Division Instead of Integer Division
Pitfall: Using regular division (/
) instead of integer division (//
):
return 0 if count == 0 else total_sum / count # Returns float
This returns a float value, but the problem specifically asks to "round down the result to the nearest integer."
Solution: Always use integer division to ensure the result is rounded down:
return 0 if count == 0 else total_sum // count # Returns int
3. Forgetting to Handle the Empty Result Case
Pitfall: Not checking if count is zero before division:
return total_sum // count # Will raise ZeroDivisionError if count is 0
This causes a runtime error when no numbers satisfy the conditions.
Solution: Always check for the zero count case first:
return 0 if count == 0 else total_sum // count
4. Using Incorrect Variable Names or Scope
Pitfall: Using confusing or shadowing variable names:
sum = 0 # 'sum' shadows built-in function
for nums in nums: # Confusing: using 'nums' as loop variable
if nums % 6 == 0:
sum += nums
Solution: Use clear, descriptive variable names that don't conflict with built-ins:
total_sum = 0 for num in nums: # Clear distinction between collection and element if num % 6 == 0: total_sum += num
Which two pointer techniques do you use to check if a string is a palindrome?
Recommended Readings
Math for Technical Interviews How much math do I need to know for technical interviews The short answer is about high school level math Computer science is often associated with math and some universities even place their computer science department under the math faculty However the reality is that you
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Want a Structured Path to Master System Design Too? Don’t Miss This!