Given two non-negative integers low
and high
, write a function to efficiently count the number of odd numbers between low
and high
(inclusive).
Examples:
Input: low = 3
, high = 7
Output: 3
Explanation: The odd numbers between 3 and 7 are [3, 5, 7]
. The count is 3.
Input: low = 8
, high = 10
Output: 1
Explanation: The odd numbers between 8 and 10 are [9]
. The count is 1.
Input: low = 2
, high = 6
Output: 2
Explanation: The odd numbers between 2 and 6 are [3,5]
. The count is 2.
Input: low = 2
, high = 3
Output: 1
Explanation: The odd numbers between 2 and 3 are [3]
. The count is 1.
Constraints:
0 <= low <= high <= 10^9
Your function should be optimized for both time and space complexity.
When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The simplest way to count odd numbers within a range is to check each number individually. We'll look at every number within the provided interval and determine if it's odd or not. Finally we add up the total count of odd numbers we've seen.
Here's how the algorithm would work step-by-step:
def count_odd_numbers_brute_force(low_number, high_number):
odd_number_count = 0
# Iterate through the numbers in the range
for current_number in range(low_number, high_number + 1):
# Check if the current number is odd
if current_number % 2 != 0:
# Increment the odd number count
odd_number_count += 1
return odd_number_count
The optimal approach finds the number of odd integers within a range by leveraging mathematical properties. We avoid checking each number individually by directly calculating the count based on the range's start and end points.
Here's how the algorithm would work step-by-step:
def count_odd_numbers(low_number, high_number):
number_of_integers = (high_number - low_number) + 1
odd_number_estimate = number_of_integers // 2
# Check if both numbers are even
if low_number % 2 == 0 and high_number % 2 == 0:
return odd_number_estimate
#If either number is odd, increment the result
else:
odd_number_estimate += 1
return odd_number_estimate
Case | How to Handle |
---|---|
low and high are equal and even | Return 0 since the single number in the range is not odd. |
low and high are equal and odd | Return 1 since the single number in the range is odd. |
low and high are consecutive even numbers | Return 0 because there are no odd numbers between two consecutive even numbers. |
low and high are consecutive odd numbers | Return 2 because the range includes both odd numbers. |
low is even and high is odd | The number of odd numbers is (high - low) / 2 + 1. |
low is odd and high is even | The number of odd numbers is (high - low) / 2 + 1. |
low and high are both even | The number of odd numbers is (high - low) / 2. |
low and high are both odd | The number of odd numbers is (high - low) / 2 + 1. |