Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.
Example 1:
Input: left = 5, right = 7 Output: 4
Example 2:
Input: left = 0, right = 0 Output: 0
Example 3:
Input: left = 1, right = 2147483647 Output: 0
Constraints:
0 <= left <= right <= 231 - 1When 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 brute force approach to finding the bitwise AND of a range of numbers involves directly calculating the bitwise AND. We'll do this by looking at each number in the range one at a time and updating our running bitwise AND value.
Here's how the algorithm would work step-by-step:
def range_bitwise_and_brute_force(range_start, range_end):
# Initialize the result with the starting number in the range
bitwise_and_result = range_start
# Iterate through the numbers in the range (excluding the start)
for current_number in range(range_start + 1, range_end + 1):
# Update the result by bitwise ANDing with the current number
bitwise_and_result = bitwise_and_result & current_number
return bitwise_and_resultThe goal is to find the common bits that are set across all numbers in the given range. The efficient way to do this involves identifying and eliminating the differing bits from the right until we reach a common prefix.
Here's how the algorithm would work step-by-step:
def range_bitwise_and(left_number, right_number):
shift_count = 0
# Keep shifting until the numbers are equal.
while left_number != right_number:
left_number >>= 1
right_number >>= 1
shift_count += 1
# Common bits found, shift back to original position.
return left_number << shift_count| Case | How to Handle |
|---|---|
| left > right | If left > right, the range is invalid, and the bitwise AND is effectively 0, so return 0. |
| left == right | If left equals right, the range consists of a single number; return that number (left). |
| left and right are both 0 | If both are 0, then result is 0. |
| left is 0, right is a large number | This requires bitwise ANDing 0 with every number up to right, resulting in 0; algorithm needs to handle large ranges efficiently. |
| left and right are consecutive powers of 2 | Bitwise AND of two consecutive powers of 2 will be 0. |
| left and right are very large numbers close to the maximum integer value | The bitwise AND operation must be performed accurately without integer overflow or unexpected behavior when working with large values. |
| left and right differ by only one | Handles this normally, doing the bitwise AND of only those two numbers. |
| Large difference between left and right (e.g., left = 1, right = 2^31 - 1) | Algorithm's time complexity should be logarithmic to avoid timeout issues related to large differences. |