Python 2980.py
class Solution:
def hasTrailingZeros(self, nums: List[int]) -> bool:
# look for at least two even numbers
return reduce(lambda a, b: a + ((b & 1) ^ 1), [ 0 ] + nums) > 1
Difficulty
and has an acceptance rate of about 72% (70k+ submissions).
Typical patterns to solve this problem:
- Array
- Bit Manipulation
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 Solution class implements a single method, hasTrailingZeros, which determines whether a given list of integers contains at least two even numbers. The implementation relies on functional programming constructs-specifically reduce and a lambda expression-to count even elements without an explicit loop. The result of the reduction is compared against the threshold 1 to produce a Boolean answer.
Core Logic
The method begins by extending the input list with a leading zero:
[0] + nums
This ensures that the first argument supplied to the reduce function serves as an initial accumulator value. By doing so, the code avoids passing an explicit initial parameter to reduce, which can simplify the call signature.
The reduction itself is performed with the following lambda:
lambda a, b: a + ((b & 1) ^ 1)
Here, a represents the running total of even numbers encountered so far, while b is the current element from the extended list. The expression (b & 1) extracts the least-significant bit of b, yielding 0 for even numbers and 1 for odd numbers. Applying the bitwise XOR with 1 (^ 1) flips this result, turning even numbers into 1 and odd numbers into 0. Adding this value to a increments the count only when b is even.
The final Boolean result is produced by comparing the accumulated count to the constant 1:
> 1
If the count exceeds 1, the method returns True, indicating that at least two even numbers are present; otherwise, it returns False.
Edge Cases Handled
When the input list is empty, the extended list becomes [0]. The reduction processes only this single element, resulting in a count of 0. The comparison 0 > 1 yields False, correctly indicating the absence of two even numbers.
For a single-element list, the reduction counts that element if it is even, producing a count of 1. The comparison 1 > 1 is also False, reflecting that exactly one even number does not satisfy the “at least two” requirement.
If all elements are odd, the bitwise expression evaluates to 0 for each element, leaving the accumulator unchanged at 0. The final comparison again returns False.
When the list contains two or more even numbers, each even element contributes 1 to the accumulator. Once the count reaches 2, the comparison 2 > 1 evaluates to True, and the method returns True.
Performance Optimizations
The implementation leverages bitwise operations (& and ^) to test parity, which are generally faster than arithmetic modulo operations (% 2). By directly manipulating bits, the code minimizes computational overhead for each element.
Using reduce eliminates the need for an explicit Python for loop, allowing the interpreter to execute the accumulation in a tight, C-level callback. This can reduce the overhead associated with loop control structures.
Prepending a zero to the list avoids the optional initial argument to reduce. While both approaches are functionally equivalent, the chosen pattern sidesteps an extra function call that would be required to supply an initial accumulator, yielding a marginal speed benefit.
The lambda expression combines the parity test and the increment operation into a single expression, reducing the number of intermediate objects created during execution. This compact formulation contributes to lower memory churn and faster evaluation.
ELI5 - Simplified Explanation
Imagine you have a big basket full of number blocks. Each block has a special secret sign that tells you if it is an even number, which means it can be split perfectly into two equal piles without leaving any leftovers. In math land, even numbers always end in a zero when you look at them in a special code called binary. When you have at least two of these even blocks, you can put their secret zeros together at the end of a long number to make a trailing zero.
This code acts like a little helper robot that goes through the basket one block at a time. It keeps a tally of every even block it finds. It starts with zero on its counter and then checks each block. Every time it spots an even one, it adds one to its tally. Once it finishes checking all the blocks in the basket, it looks at how many even ones it found. If the count is bigger than one, it knows that those even blocks can work together to make trailing zeros.
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 | C++ | Go | Python | TS | ||
| Progiez | Java | C++ | Python | ||||
| github | charles-wangkai | Java | |||||
| fsq | C++ | ||||||
| JoshCrozier | JS | ||||||
| varunu28 | Java | ||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||
| WalkCCC | C++, Python, Java | ||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||
| Progiez | C++, Java, Python | ||||||
| charles-wangkai | Java | ||||||
| fsq | C++ | ||||||
| JoshCrozier | JavaScript | ||||||
| varunu28 | Java |
Videos
Similar Problems
- problem 1523: Count Odd Numbers in an Interval Range
- problem 2710: Remove Trailing Zeros From a String
Solved On The Same Day
- problem 2899: Last Visited Integers
- problem 2923: Find Champion I
- problem 2996: Smallest Missing Integer Greater Than Sequential Prefix Sum
- problem 3001: Minimum Moves to Capture The Queen
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