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
Difficulty
and has an acceptance rate of about 64% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Math
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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 |
Videos
Similar Problems
- problem 1018: Binary Prefix Divisible By 5
Solved On The Same Day
- problem 2460: Apply Operations to an Array
- problem 2410: Maximum Matching of Players With Trainers
- problem 2420: Find All Good Indices
- problem 2486: Append Characters to String to Make Subsequence
Extra
- 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