Python 1550.py
class Solution:
def threeConsecutiveOdds(self, arr: List[int]) -> bool:
return any((arr[i - 2] & 1) + (arr[i - 1] & 1) + (arr[i] & 1) == 3 for i in range(2, len(arr)))
Difficulty
and has an acceptance rate of about 69% (600k+ submissions).
Typical patterns to solve this problem:
- Array
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 threeConsecutiveOdds method determines whether an input list of integers contains any three adjacent elements that are all odd. It returns a Boolean value: True when such a triple exists, otherwise False. The implementation relies on a compact generator expression combined with Python’s built-in any function.
Key Steps
The core logic is expressed in a single return statement, but it can be broken down into distinct conceptual steps.
Step 1 - Iteration over candidate positions
for i in range(2, len(arr))
The loop variable i starts at index 2, ensuring that the indices i-2, i-1, and i are always valid. When the input list has fewer than three elements, range(2, len(arr)) produces an empty sequence, causing the generator to yield no values and any to return False automatically.
Step 2 - Detecting odd numbers with a bitwise test
arr[index] & 1
Applying the bitwise AND operator with 1 isolates the least-significant bit of each integer. The result is 1 for odd numbers and 0 for even numbers, providing a fast, branch-free way to test oddness without invoking modulo arithmetic.
Step 3 - Summing the odd-ness flags of three consecutive elements
(arr[i - 2] & 1) + (arr[i - 1] & 1) + (arr[i] & 1) == 3
Each of the three flag values is either 0 or 1. Their sum equals 3 only when all three flags are 1, i.e., when the three examined elements are odd. The equality comparison yields a Boolean that indicates whether the current triple satisfies the condition.
Step 4 - Short-circuit evaluation with any
any( ... for i in range(2, len(arr)))
The generator feeds the Boolean result of the triple-odd test to any. As soon as a True value appears, any stops iterating and returns True. If the generator exhausts all candidates without producing True, any returns False. This lazy evaluation avoids unnecessary work once a qualifying triple is found.
Edge Cases Handled
When the input list is empty or contains one or two elements, the range used for iteration is empty, so the generator yields no values and any returns False. This behavior correctly reflects that a triple of consecutive odds cannot exist in such short sequences.
Negative integers are processed correctly because the bitwise oddness test (& 1) depends only on the least-significant bit, which is defined for two’s-complement representation used by Python’s integers.
Lists that contain a mixture of odd and even numbers, including large magnitude values, are handled uniformly because the oddness test does not depend on the numeric size, only on the lowest bit.
Performance Optimizations
The implementation leverages several low-overhead techniques. The bitwise & 1 operation is faster than the more common % 2 modulo check, eliminating division and reducing CPU cycles per element.
Using a generator expression inside any means that no intermediate list of Boolean values is created; each triple is evaluated on-the-fly, keeping memory usage minimal.
The short-circuit nature of any ensures that the loop terminates at the first successful detection, preventing the algorithm from scanning the remainder of the list when it is unnecessary.
Overall, the code combines concise expression with efficient primitive operations, delivering a solution that runs quickly even on large input arrays.
ELI5 - Simplified Explanation
Imagine a long train of numbers sitting in a line. Some of these numbers are odd, which means they cannot be split into two equal teams. The goal of this code is to check if there are three odd numbers standing right next to each other anywhere in the line.
The code starts by looking at the first three numbers in the line. It asks if the first, the second, and the third are all odd. If they are, it finds what it is looking for. If not, it moves its vision just one spot over to look at the next set of three numbers. It keeps moving along the line one step at a time, looking at every possible group of three neighbors. Using the little ampersand symbol is a clever way to peek at the very end of a number to see if it is odd or even. If it ever sees three odd numbers in a row, the search is finished.
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 | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | Go | TS | ||||||
| Progiez | C++ | Python | Java | ||||||||
| github | AdelDaniel | Dart | |||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| AdelDaniel | Dart | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 1629: Slowest Key
- problem 1637: Widest Vertical Area Between Two Points Containing No Points
- problem 1684: Count the Number of Consistent Strings
- problem 1630: Arithmetic Subarrays
- problem 1663: Smallest String With A Given Numeric Value
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