Count Odd Numbers in an Interval Range - Problem
Given two non-negative integers low and high, return the count of odd numbers in the range [low, high] (inclusive).
An odd number is any integer that is not divisible by 2. For example, 1, 3, 5, 7, 9 are odd numbers, while 2, 4, 6, 8 are even numbers.
Example: If low = 3 and high = 7, the numbers in range are [3, 4, 5, 6, 7]. Among these, the odd numbers are [3, 5, 7], so the answer is 3.
Your task is to find an efficient way to count odd numbers without iterating through each number in the range, especially when the range is very large.
Input & Output
example_1.py โ Small Range
$
Input:
low = 3, high = 7
โบ
Output:
3
๐ก Note:
The odd numbers in range [3,7] are: 3, 5, 7. Total count = 3.
example_2.py โ Even Boundaries
$
Input:
low = 8, high = 10
โบ
Output:
1
๐ก Note:
The numbers in range [8,10] are: 8, 9, 10. Only 9 is odd. Total count = 1.
example_3.py โ Single Number
$
Input:
low = 1, high = 1
โบ
Output:
1
๐ก Note:
Range contains only one number: 1. Since 1 is odd, the count is 1.
Constraints
- 0 โค low โค high โค 109
- Both low and high are non-negative integers
- Note: The range can be very large (up to 1 billion), making brute force inefficient
Visualization
Tap to expand
Understanding the Visualization
1
Recognize the Pattern
In sequence 1,2,3,4,5,6,7... every other number is odd
2
Count Formula
From 1 to N, there are (N+1)//2 odd numbers
3
Range Calculation
Use subtraction to get count in specific range
4
Instant Result
O(1) solution works for any range size
Key Takeaway
๐ฏ Key Insight: Instead of checking each number individually, we use the mathematical property that exactly half of any consecutive sequence of integers are odd numbers, allowing us to calculate the count in constant time.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code