Problem 2455

Abstract / Summary

Find the average of all even numbers in an array that are also divisible by three.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 2455.py

class Solution:
    def averageValue(self, nums: List[int]) -> int:
        three = [ n for n in nums if n % (2 * 3) == 0 ]
        return sum(three) // len(three) if three else 0
4 lines | 184 bytes | submitted February 18, 2024 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 64% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single method averageValue. The method receives a list of integers and computes the average of those elements that are multiples of both 2 and 3, i.e., multiples of 6. The result is returned as an integer using floor division, and a value of 0 is produced when no qualifying elements exist.

Key Steps

The first logical step isolates the numbers that satisfy the divisibility condition. This is achieved with a list comprehension that iterates over the input list and applies a modulo test against the product 2 * 3. The comprehension builds a new list containing only the qualifying elements.

three = [n for n in nums if n % (2 * 3) == 0]

The second step aggregates the filtered values. The built-in sum function computes the total of the elements in the filtered list, while len determines how many elements were collected. The method then performs integer division to obtain the average. A conditional expression guards against division by zero by returning 0 when the filtered list is empty.

return sum(three) // len(three) if three else 0

Edge Cases

When the input list contains no numbers divisible by 6, the list comprehension yields an empty list. The conditional expression if three else 0 detects this situation and bypasses the division operation, directly returning 0. This prevents a potential ZeroDivisionError and ensures that the method always returns a valid integer result, even for an empty input list or a list lacking qualifying elements.

Performance Optimizations

The use of a list comprehension consolidates the filtering logic into a single, concise expression that runs in linear time relative to the size of the input list. By constructing the filtered list in one pass, the code avoids multiple traversals of the data. The reliance on Python’s built-in sum and len functions leverages highly optimized C-level implementations, reducing overhead compared to manual loops. Additionally, the arithmetic expression 2 * 3 is evaluated once at compile time, eliminating repeated computation of the divisor during iteration. The final integer division (//) provides the required floor behavior without the need for an explicit conversion step.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a group of numbered blocks laid out on the floor. First, the code looks for any blocks that can be divided perfectly by both two and three at the same time, which is the same as being divided by six. It picks those specific blocks up and puts them into a separate pile. After that, it adds up all the numbers written on the blocks in that new pile. Finally, it divides that big total by the number of blocks in the pile to find the middle value. If the pile is empty, it just stops.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.59 | σ = 1.71

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster Java C++ Python TS
WalkCCC Java C++ Python
leetcode.ca Java Go C++ C Python Rust TS
Progiez Java C++ Python
github charles-wangkai Java
DimitrisJim C
fartem Ruby
fsq C++
JoshCrozier JS
muhammadfarhankt Go
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
charles-wangkai Java
DimitrisJim C
fartem Ruby
fsq C++
JoshCrozier JavaScript
muhammadfarhankt Go
varunu28 Java
24 links | 11 authors | 9 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

5 solutions   February 18, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality