1523 Count Odd Numbers in an Interval Range
![]() |
Count Odd Numbers in an Interval Range Python C++ Java |
In this article, we'll explore the solution to LeetCode problem 1523: Count Odd Numbers in an Interval Range. Given two non-negative integers, low
and high
, the task is to return the count of odd numbers between the two values (inclusive).
🧠 What are Odd Numbers?
Odd numbers are numbers that are not divisible by 2. That means if a number leaves a remainder of 1
when divided by 2, it is considered odd.
Example:
1, 3, 5, 7, 9...
📝 Problem Statement
Given two non-negative integers low
and high
, return the total count of odd numbers in the inclusive range [low, high]
.
🔢 Example 1
Input:low = 3, high = 7
Output: 3
Explanation: The odd numbers in this range are [3, 5, 7].
🔢 Example 2
Input:Output: 1 Explanation:low = 8, high = 10
Only 9 is an odd number between 8 and 10.
✅ Optimized Approach
Instead of checking each number individually, we can use a mathematical formula to calculate the count of odd numbers:
Count = ((high - low) // 2) + (1 if low % 2 != 0 or high % 2 != 0 else 0)
This works because odd numbers alternate every two steps, and if either boundary is odd, we add one extra.
💻 Python Code
def countOdds(low: int, high: int) -> int:
return ((high - low) // 2) + (1 if low % 2 != 0 or high % 2 != 0 else 0)
💻 C++ Code
class Solution {
public:
int findOddCount(int min, int max) {
if (!(min & 1)) {
min++;
}
return min > max ? 0 : (max - min) / 2 + 1;
}
};
💻 Java Code
class Solution {
public int countOddNumbers(int start, int end) {
// Increment start if it's even.
if ((start & 1) == 0) {
start++;
}
// Calculate the number of odd numbers in the range.
return start > end ? 0 : (end - start) / 2 + 1;
}
}
🧠 Time and Space Complexity
- Time Complexity: O(1) – No loops, just arithmetic operations.
- Space Complexity: O(1) – No extra memory used.
🎯 Conclusion
This problem teaches how simple mathematical reasoning can replace brute-force loops. It’s a perfect example of writing efficient, optimized code for a seemingly simple problem. Try implementing it in your favorite language and practice edge cases!