#1523
Count Odd Numbers in an Interval Range
EasyMathMathematical CountingParity Check
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(1) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(1)Space O(1)
Instead of iterating through all numbers, we can use a mathematical approach to directly calculate the number of odd numbers in the range. This is much faster and efficient, especially for large ranges.
⚙️
Algorithm
3 steps- 1Step 1: Calculate the total number of integers in the range: total = high - low + 1.
- 2Step 2: If total is even, return total / 2 (half will be odd).
- 3Step 3: If total is odd, check the parity of low. If low is odd, return (total / 2) + 1; otherwise, return total / 2.
solution.py8 lines
1# Full working Python code
2low, high = 3, 7
3total = high - low + 1
4if total % 2 == 0:
5 count = total // 2
6else:
7 count = (total // 2) + (1 if low % 2 != 0 else 0)
8print(count)ℹ
Complexity note: The time complexity is O(1) because we are performing a constant number of operations regardless of the size of the range. The space complexity is also O(1) as we are using a constant amount of space.
- 1If the range has an even number of integers, the count of odd and even numbers will be the same.
- 2If the range has an odd number of integers, the count of odd numbers will depend on whether the starting number (low) is odd or even.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.