C++ 1523.cpp
class Solution {
public:
int countOdds(int low, int high) {
if (low == high)
return low & 1;
auto result = 0;
if (low & 1)
{
low++;
result++;
}
if (high & 1)
{
high--;
result++;
}
return result + (high - low) / 2;
}
};
Difficulty
and has an acceptance rate of about 55% (1+ million submissions).
Typical patterns to solve this problem:
- 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 countOdds method computes how many odd integers lie in the inclusive range [low, high]. It does so with a small amount of arithmetic and a couple of bit-wise checks, guaranteeing a single pass over the numeric interval without any loops or recursion. The implementation is compact, deterministic, and works for any pair of non-negative integers where low is less than or equal to high.
Core Logic
The function begins by handling the degenerate case where the interval consists of a single number.
if (low == high)
return low & 1;
The expression low & 1 extracts the least-significant bit, yielding 1 when low is odd and 0 otherwise. This single-line return instantly resolves the answer for a range of length one.
When the interval contains more than one element, the algorithm proceeds to normalize the bounds so that both become even. Two separate blocks adjust low and high if they are odd, while simultaneously counting the odd numbers that have been removed from the ends of the range.
auto result = 0;
if (low & 1)
{
low++;
result++;
}
if (high & 1)
{
high--;
result++;
}
If low is odd, it is incremented to the next even integer and the counter result is increased by one, reflecting the odd number that has just been accounted for. The same pattern applies to high when it is odd, decrementing it to the preceding even integer and adding one to result.
At this point both low and high are guaranteed to be even, and any odd numbers that were originally at the boundaries have already been tallied. The remaining interval [low, high] now contains only even numbers at its ends, which means the odd numbers are perfectly interleaved with the evens. The count of those interior odds can be derived from the distance between the adjusted bounds.
return result + (high - low) / 2;
The difference high - low represents the total span of the even-adjusted interval. Dividing by two yields the number of odd positions inside that span because every second integer is odd. Adding this to the previously accumulated result gives the final count.
Edge-Case Handling
The code explicitly addresses the situation where low equals high. In that scenario the early return avoids any further arithmetic that could otherwise produce an incorrect result (for example, the subtraction high - low would be zero, and the subsequent division would miss the single odd value if present).
When low is odd, the increment low++ moves the lower bound to the next even integer, ensuring that the subsequent arithmetic works on an even-aligned range. The same logic applies when high is odd, with high-- moving the upper bound down to an even number. These adjustments guarantee that the interior calculation (high - low) / 2 always operates on an interval whose endpoints are even, which simplifies the derivation of the interior odd count.
If both low and high are even from the start, the conditional blocks are bypassed, leaving result at zero. The interior formula then directly computes the number of odds between the two even bounds.
Performance Characteristics
The implementation runs in constant time because it performs a fixed number of operations regardless of the size of the input interval. The use of bitwise & 1 to test oddness is a low-cost operation on modern processors. Adjusting the bounds with simple increments or decrements avoids any looping constructs, and the final arithmetic expression (high - low) / 2 is a single integer division.
All intermediate values are stored in primitive integer types, eliminating any heap allocation or additional data structures. This minimal memory footprint contributes to the overall efficiency, making the function suitable for performance-critical contexts where it may be invoked repeatedly.
The algorithm also benefits from branch predictability: the two if statements each test a single bit, and the subsequent paths are straightforward, allowing modern CPUs to predict and execute them with minimal pipeline disruption.
Overall, the method delivers a fast, deterministic count of odd numbers in any inclusive integer range using only elementary arithmetic and bitwise operations.
ELI5 - Simplified Explanation
Imagine you have a big box of numbered blocks starting from a low number and going up to a high number. The goal is to count how many of these blocks have an odd number written on them. An odd number is any number that ends in one, three, five, seven, or nine.
First, the code checks if the low number and the high number are the same. If they are, it just looks at that one number to see if it is odd. If the range has more than one number, the code starts a counter at zero. It looks at the low number first. If the low number is odd, it marks it down by adding one to the counter and then moves to the next number. Then it looks at the high number. If that one is odd, it marks it down by adding one to the counter and then moves back to the number right before it.
After dealing with the two ends, every single pair of numbers left in the middle will have exactly one odd number and one even number in it. Because of this, the code takes the remaining distance between the new low and high numbers and divides it by two to count those extra odd numbers. Adding all these pieces together gives the total count of every odd number in the whole set.
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++ | Java | Python | TS | |||||||||
| WalkCCC | C++ | |||||||||||||
| leetcode.ca | C++ | Java | Python | C | Go | PHP | Rust | TS | ||||||
| Progiez | C++ | Java | Python | |||||||||||
| github | black-shadows | C++ | ||||||||||||
| charles-wangkai | Java | |||||||||||||
| DimitrisJim | C | |||||||||||||
| everthis | JS | |||||||||||||
| fartem | Ruby | |||||||||||||
| FelixFan1122 | Java | |||||||||||||
| fsq | C++ | |||||||||||||
| haoel | C++ | |||||||||||||
| JoshCrozier | JS | |||||||||||||
| keineahnung2345 | C++ | |||||||||||||
| lkwq007 | Python | |||||||||||||
| martianoff | Scala | |||||||||||||
| muhammadfarhankt | SQL | |||||||||||||
| suxrobGM | C# | |||||||||||||
| trung-hn | Python | |||||||||||||
| varunu28 | Java | |||||||||||||
| vthwang | Java | |||||||||||||
| withaarzoo | C++ | |||||||||||||
| YuriSpiridonov | Python | |||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||||
| WalkCCC | C++ | |||||||||||||
| leetcode.ca | C, C++, Go, Java, PHP, Python, Rust, TypeScript | |||||||||||||
| Progiez | C++, Java, Python | |||||||||||||
| black-shadows | C++, C++ | |||||||||||||
| charles-wangkai | Java | |||||||||||||
| DimitrisJim | C | |||||||||||||
| everthis | JavaScript | |||||||||||||
| fartem | Ruby | |||||||||||||
| FelixFan1122 | Java | |||||||||||||
| fsq | C++ | |||||||||||||
| haoel | C++ | |||||||||||||
| JoshCrozier | JavaScript | |||||||||||||
| keineahnung2345 | C++ | |||||||||||||
| lkwq007 | Python | |||||||||||||
| martianoff | Scala | |||||||||||||
| muhammadfarhankt | SQL | |||||||||||||
| suxrobGM | C# | |||||||||||||
| trung-hn | Python | |||||||||||||
| varunu28 | Java | |||||||||||||
| vthwang | Java | |||||||||||||
| withaarzoo | C++ | |||||||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
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