Count Odd Numbers in an Interval Range Problem
#1523
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1523.
Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive).
Example 1:
Input: low = 3, high = 7
Output: 3
Explanation: The odd numbers between 3 and 7 are [3,5,7].
Example 2:
Input: low = 8, high = 10
Output: 1
Explanation: The odd numbers between 8 and 10 are [9].
Constraints:
0 <= low <= high <= 10^9
Solution
Approach: Count Odds Up to a Bound
The range can contain up to 109 numbers, so instead of looping we count with a formula.
The numbers 0, 1, ..., x contain (x + 1) / 2 odd numbers (integer division): 0..4 has 1, 3, which is 5 / 2 = 2, and 0..5 has 1, 3, 5, which is 6 / 2 = 3.
The odd numbers in [low, high] are the odd numbers in [0, high] minus those in [0, low - 1], which is (high + 1) / 2 - low / 2.
This also handles low = 0 and low = high with no special cases, e.g. low = high = 7 gives 4 - 3 = 1.
Complexity: O(1) time and O(1) space.
class Solution:
def countOdds(self, low: int, high: int) -> int:
# [0, x] holds (x + 1) // 2 odd numbers; subtract those below low
return (high + 1) // 2 - low // 2