#2455

Average Value of Even Numbers That Are Divisible by Three

Easy
ArrayMathArrayMathematical Properties
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution focuses on recognizing that any number that is both even and divisible by 3 is also divisible by 6. This allows us to simplify our checks and directly filter for numbers divisible by 6.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a sum variable to 0 and a count variable to 0.
  2. 2Step 2: Loop through each number in the array.
  3. 3Step 3: For each number, check if it is divisible by 6.
  4. 4Step 4: If it is, add it to the sum and increment the count.
  5. 5Step 5: After the loop, if count is 0, return 0. Otherwise, return the sum divided by count, rounded down.
solution.py10 lines
1# Full working Python code
2
3def average_even_divisible_by_three(nums):
4    total_sum = 0
5    count = 0
6    for num in nums:
7        if num % 6 == 0:
8            total_sum += num
9            count += 1
10    return total_sum // count if count > 0 else 0

Complexity note: The complexity remains O(n) since we still iterate through the array once. The space complexity is O(1) as we are using a fixed amount of space.

  • 1Recognizing that even numbers divisible by 3 are also divisible by 6 simplifies the problem.
  • 2Using a single pass through the array is efficient and avoids unnecessary checks.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.