Average Value of Even Numbers That Are Divisible by Three - 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.

Input & Output

Example 1 — Mixed Numbers
$ Input: nums = [1,3,6,10,12,15]
Output: 9
💡 Note: Numbers divisible by both 2 and 3: 6 (even, 6÷3=2) and 12 (even, 12÷3=4). Average = (6+12)/2 = 9
Example 2 — No Valid Numbers
$ Input: nums = [1,2,4,7,10]
Output: 0
💡 Note: No numbers are both even AND divisible by 3. 2,4,10 are even but not divisible by 3. Return 0.
Example 3 — Single Valid Number
$ Input: nums = [4,4,9,6]
Output: 6
💡 Note: Only 6 is both even and divisible by 3. Average = 6/1 = 6

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Even Numbers Divisible by 3 INPUT nums array: 1 3 6 10 12 15 Divisible by 6 Not divisible by 6 Divisibility Check: 1 % 6 = 1 (skip) 3 % 6 = 3 (skip) 6 % 6 = 0 (OK) 10 % 6 = 4 (skip) 12 % 6 = 0 (OK) 15 % 6 = 3 (skip) ALGORITHM STEPS 1 Initialize sum = 0, count = 0 2 Loop Through Array For each num in nums 3 Check num % 6 == 0 If true: sum += num count += 1 4 Calculate Average return sum / count Valid nums: [6, 12] sum = 6 + 12 = 18 count = 2 FINAL RESULT Numbers divisible by 6: 6 12 Sum = 6 + 12 = 18 Count = 2 18 / 2 = 9 Output: 9 [OK] Average calculated Key Insight: Even numbers divisible by 3 are exactly the numbers divisible by 6 (LCM of 2 and 3). Instead of checking (num % 2 == 0) AND (num % 3 == 0), we simply check (num % 6 == 0). TutorialsPoint - Average Value of Even Numbers That Are Divisible by Three | Optimized - Check Divisibility by 6
Asked in
Amazon 12 Microsoft 8
12.0K Views
Medium Frequency
~8 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen