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
Before diving into coding, let’s clarify the problem with a few questions:
left
and right
?
0 <= left <= right <= 2^31 - 1
.left
and right
inclusive?
[left, right]
is inclusive.The key observation for solving this problem is that as numbers increase in a range, their lower bits will eventually flip to 0 due to the power-of-2 nature of binary representation:
left
and right
until they diverge. Once they differ, the remaining lower bits in a range [left, right]
will be mismatched and thus zero out in the AND result.left
and right
to the right until they are equal.left
(or right
, since now they are equal) back to the left by the same number of times to derive the result.This effectively identifies the common prefix bits in the numbers within the range.
Here is how you can implement this in Python:
def rangeBitwiseAnd(left: int, right: int) -> int:
shift = 0
# Find the common prefix
while left < right:
left >>= 1
right >>= 1
shift += 1
# Shift the common prefix back to its original position
return left << shift
left
is equal to right
.max_val
) times, where max_val
is the maximum integer value.O(log n)
, where n
is the range size or the magnitude of right
.This algorithm ensures that we efficiently find the bitwise AND of a range of numbers by focusing on their bits directly and iterating only until necessary.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?