Count Odd Numbers in an Interval Range - Problem

Given two non-negative integers low and high, return the count of odd numbers between low and high (inclusive).

An odd number is any integer that is not divisible by 2. For example, 1, 3, 5, 7, 9 are odd numbers.

Example: If low = 3 and high = 7, the numbers in range are [3, 4, 5, 6, 7]. The odd numbers are 3, 5, 7, so the answer is 3.

Input & Output

Example 1 — Basic Range
$ Input: low = 3, high = 7
Output: 3
💡 Note: Numbers in range [3,4,5,6,7]. Odd numbers are 3, 5, 7, so count is 3.
Example 2 — Even Range
$ Input: low = 8, high = 10
Output: 1
💡 Note: Numbers in range [8,9,10]. Only 9 is odd, so count is 1.
Example 3 — Single Number
$ Input: low = 1, high = 1
Output: 1
💡 Note: Range contains only 1, which is odd, so count is 1.

Constraints

  • 0 ≤ low ≤ high ≤ 109

Visualization

Tap to expand
Count Odd Numbers in an Interval Range INPUT 3 low 4 5 6 7 high Odd numbers Even low = 3 high = 7 Range: [3, 4, 5, 6, 7] Odd: 3, 5, 7 Count needed: ? ALGORITHM STEPS 1 Calculate Range total = high - low + 1 7 - 3 + 1 = 5 2 Formula Insight Half are odd (rounded up if range starts odd) 3 Apply Formula count = (high+1)/2 - low/2 (7+1)/2 - 3/2 = 8/2 - 3/2 = 4 - 1 = 3 4 Return Result O(1) time complexity O(1) space complexity FINAL RESULT Odd numbers found: 3 5 7 Output 3 OK - Verified 3 odd numbers in range [3, 7] Key Insight: Instead of iterating through all numbers (O(n)), use math: count = (high+1)/2 - low/2. This counts odd numbers from 1 to high, then subtracts odd numbers from 1 to (low-1). Integer division automatically handles floor operations, giving O(1) time complexity. TutorialsPoint - Count Odd Numbers in an Interval Range | Optimal O(1) Solution
Asked in
Microsoft 25 Apple 20 Google 15
180.0K Views
Medium Frequency
~5 min Avg. Time
2.3K 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