The Leetcode problem "Count Odd Numbers in an Interval Range" asks you to determine how many odd integers exist within a given inclusive interval. Specifically, you are given two integers, low
and high
, which define the start and end of the interval (both inclusive). Your task is to return the count of all odd numbers that are within this range.
low
and high
are integers, and low <= high
.
The first instinct when tackling this problem might be to iterate through every number from low
to high
and count how many of them are odd. This brute-force approach is straightforward, but it can be inefficient, especially if the interval is large.
However, since the task is to count (not list) the odd numbers, we can look for a mathematical shortcut. Odd numbers in any interval alternate with even numbers, so there is a predictable pattern. By leveraging simple arithmetic, we can avoid looping entirely and compute the answer in constant time.
The key is to realize that, for any two numbers, the total number of odd numbers between them can be calculated with a formula, rather than checking each value individually.
Let's break down how to efficiently count the odd numbers in the interval [low, high]
:
high - low + 1
.
(high - low) // 2 + 1
gives the count if either low
or high
is odd. If both are even, the count is (high - low) // 2
.
(high + 1) // 2 - (low // 2)
. This works because (x + 1) // 2
gives the count of odd numbers from 1 to x
, so subtracting gives the count in [low, high]
.
This approach eliminates the need for loops and ensures the solution runs in constant time.
Let's consider an example where low = 3
and high = 7
.
(high + 1) // 2 - (low // 2)
(7 + 1) // 2 = 8 // 2 = 4
3 // 2 = 1
4 - 1 = 3
This process works for any interval, including those where low
and high
are both even, both odd, or one of each.
class Solution:
def countOdds(self, low: int, high: int) -> int:
return (high + 1) // 2 - (low // 2)
class Solution {
public:
int countOdds(int low, int high) {
return (high + 1) / 2 - (low / 2);
}
};
class Solution {
public int countOdds(int low, int high) {
return (high + 1) / 2 - (low / 2);
}
}
/**
* @param {number} low
* @param {number} high
* @return {number}
*/
var countOdds = function(low, high) {
return Math.floor((high + 1) / 2) - Math.floor(low / 2);
};
low
to high
and check each number, the time complexity is O(N), where N = high - low + 1
.
The optimized approach is much faster and preferred, especially for large intervals.
In this problem, we leveraged the predictable alternation of odd and even numbers to derive a simple formula for counting odd numbers in any interval. Instead of iterating through the range, we used arithmetic to achieve a constant-time solution. This approach is both elegant and efficient, demonstrating how mathematical reasoning can simplify what might otherwise seem like a computational problem.