Average Value of Even Numbers That Are Divisible by Three - Problem

You're given an array of positive integers and need to find the average value of numbers that satisfy two specific conditions:

  • The number must be even (divisible by 2)
  • The number must be divisible by 3

In other words, you're looking for numbers that are divisible by both 2 and 3 (which means divisible by 6!).

Return the integer average of all such numbers. If no numbers meet the criteria, return 0.

Note: The average should be rounded down to the nearest integer (floor division).

Example: In array [4, 6, 7, 9, 12], only 6 and 12 are both even and divisible by 3. Average = (6 + 12) / 2 = 9

Input & Output

example_1.py โ€” Basic case
$ Input: [4, 6, 7, 9, 12, 18]
โ€บ Output: 12
๐Ÿ’ก Note: Numbers divisible by both 2 and 3 (i.e., divisible by 6): 6, 12, 18. Average = (6 + 12 + 18) / 3 = 36 / 3 = 12
example_2.py โ€” No valid numbers
$ Input: [1, 3, 5, 7, 9]
โ€บ Output: 0
๐Ÿ’ก Note: None of these numbers are even, so none can be divisible by both 2 and 3. Return 0.
example_3.py โ€” Single valid number
$ Input: [6]
โ€บ Output: 6
๐Ÿ’ก Note: Only one number: 6. It's divisible by both 2 and 3. Average = 6 / 1 = 6

Constraints

  • 1 โ‰ค nums.length โ‰ค 1000
  • 1 โ‰ค nums[i] โ‰ค 1000
  • All integers are positive
  • Return 0 if no valid numbers exist

Visualization

Tap to expand
๐ŸŽฏ Quality Control InspectorFinding candies that are BOTH blue (even) AND have 3 ingredients (รท3)4โŒ Red candy6โœ… Blue + 3 ing.7โŒ Red candy9โŒ Green candy12โœ… Blue + 3 ing.18โœ… Blue + 3 ing.Premium Shipment Quality ControlInspector's Report: 3 candies passed quality checkTotal Quality Score: 6 + 12 + 18 = 36Average Quality: 36 รท 3 = 12โœ… APPROVED: 12
Understanding the Visualization
1
Inspect Each Candy
Check if candy meets both criteria: blue AND 3 ingredients
2
Keep Running Tally
Maintain count and sum of qualifying candies
3
Calculate Quality Score
Compute average quality (sum รท count) for premium shipment
Key Takeaway
๐ŸŽฏ Key Insight: Numbers divisible by both 2 and 3 are exactly those divisible by 6. This mathematical property allows us to solve the problem efficiently in a single pass with O(1) space.
Asked in
Amazon 25 Google 18 Microsoft 12 Apple 8
28.4K Views
Medium Frequency
~8 min Avg. Time
892 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