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
Pattern Recognition: Counting Odd NumbersNumber Sequence Pattern:1odd2even3odd4even5odd6even7odd...Mathematical Formula:Count = (high + 1) รท 2 - low รท 2For range [3,7]: (7+1)รท2 - 3รท2 = 4 - 1 = 3Result: 3 odd numbers (3, 5, 7)Why This Works:โ€ข Every consecutive pair of numbers has exactly 1 odd numberโ€ข From 1 to N, there are โŒŠ(N+1)/2โŒ‹ odd numbersโ€ข Subtract to get count in any range [low, high]โ€ข Time complexity: O(1) - works for ranges up to 1 billion!
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.
Asked in
Microsoft 25 Amazon 18 Google 15 Apple 12
85.0K Views
Medium Frequency
~8 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen