Count Odd Numbers in an Interval Range

The problem asks to return the count of odd numbers between two given non-negative integers low and high (inclusive).

Approach

To count the number of odd numbers between low and high, we can use the following observations:

  1. If both low and high are even, then the number of odd numbers between them will be (high - low) / 2.
  2. If one of low or high is odd, then the number of odd numbers between them will be (high - low) / 2 + 1.

Combining the two cases, we can write the following function:

1
2
3
class Solution:
    def countOdds(self, low: int, high: int) -> int:
        return (high + 1) // 2 - low // 2

This code takes into account both cases by adding 1 to high before dividing by 2 and then subtracting low divided by 2.

Example

For low = 3 and high = 7, the odd numbers between them are [3, 5, 7], so the output is 3.

For low = 8 and high = 10, the odd numbers between them are [9], so the output is 1.

Complexity

This solution has a time complexity of O(1) and a space complexity of O(1), as it involves only simple arithmetic operations.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# @param {Integer} low
# @param {Integer} high
# @return {Integer}
def count_odds(low, high)
    if low.even? && high.even?
        return (high - low) / 2
    else
        return (high - low) / 2 + 1
    end
end