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^9This approach uses the mathematical properties of odd and even numbers. The core idea is to count the odd numbers in the range efficiently without iterating through all numbers.
Two cases arise:
- If both low and high are odd, then the range includes both `low` and `high` as odd numbers.
- Otherwise, depending on whether `low` or `high` is even, you adjust the start or the end.
The formula used is derived from these observations:
If either `low` or `high` is odd, the count is `(high - low) / 2 + 1`. Otherwise, it is `(high - low) / 2`.
This C solution uses integer arithmetic to calculate the number of odd numbers directly. The expression (high + 1) / 2 gives the count of odd numbers from 1 to high, and low / 2 gives the count of odd numbers from 1 up to just below low. Their difference provides the count of odd numbers between low and high.
C++
Java
Python
C#
JavaScript
Time Complexity: O(1)
Space Complexity: O(1)
In this approach, we iterate through the numbers from low to high and check if each number is odd by using the modulus operator. Count every number that meets the condition of being odd.
This approach, though straightforward, is less optimal for larger ranges due to its linear nature in terms of time complexity.
This C solution uses a for-loop to iterate between the low and high values, incrementing a counter whenever it encounters an odd number as determined by the modulus operator.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is (high - low + 1)
Space Complexity: O(1)
| Approach | Complexity |
|---|---|
| Mathematical Pattern Approach | Time Complexity: O(1) Space Complexity: O(1) |
| Iterative Checking Approach | Time Complexity: O(n), where n is (high - low + 1) Space Complexity: O(1) |
Count Odd Numbers in an Interval Range - Leetcode 1523 - Python • NeetCodeIO • 7,486 views views
Watch 9 more video solutions →Practice Count Odd Numbers in an Interval Range with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor