LeetCode #201 Medium

Bitwise AND of Numbers Range

Bitwise AND of Numbers Range is LeetCode 201 (Medium). Given two integers left and right, return the bitwise AND of every integer from left to right, both ends included.

Both ends lie between 0 and 2³¹ − 1, so one range can hold over two billion numbers. Visiting them one by one is far too slow; the answer has to come from the bits of the two ends.

Constraints
  • 0 <= left <= right <= 2³¹ - 1
bit-manipulation
Open on LeetCode ↗
02

Intuition

Find the highest bit where left and right differ. left has a 0 there and right has a 1, so while counting up from left the range passes a number with a 1 in that place and only 0s below it. That one number clears every lower bit of the AND, and left itself clears the differing bit.

The bits above that place are equal in left and right, and every number between them carries the same bits, so they all survive. The answer is the common binary prefix of the two ends, followed by zeros.

How to spot this pattern

An AND (or OR) over a huge run of consecutive integers cannot be computed one number at a time. Ask which bits are allowed to change inside the run: a bit that changes even once is 0 in an AND, so only the bits shared by both ends can remain.

03

Approach

Try it first

Before reading on, write 9, 10, 11 and 12 in binary and AND them by hand. Which bits do 9 and 12 share at the front, and what does the result look like after those bits? Then find a way to get that answer from 9 and 12 alone, in at most 31 steps.

1

Drop the lowest bit while the ends differ

While left != right, shift both one place to the right and add 1 to shift. While the two numbers still differ, the bit being dropped sits at or below their highest differing bit, so it is 0 in the answer.

2

The equal value is the shared prefix

When left == right, what remains is exactly the run of high bits both ends had in common. Every number in the range has these same high bits, so each of them is 1 in the AND wherever it is 1 here.

3

Shift the prefix back into place

Return left << shift. This moves the prefix back to its original bit positions and fills the shift lowest places with 0s, one for each bit that some number in the range cleared.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def rangeBitwiseAnd(self, left: int, right: int) -> int:
▶3 shift = 0
▶4 while left != right:
▶5 left >>= 1
▶6 right >>= 1
▶7 shift += 1
▶8 return left << shift
421nowshiftleft101right111570answernothing dropped yet
left5
right7
shift0
5 and 7 in binary. Only bits that stay 1 in every number from 5 to 7 can survive the AND. The loop finds them by dropping low bits until the two ends match.
421nowshiftleft101right11157≠0answer5 and 7 differ → drop the lowest bit
left5
right7
The kept bits still differ (red). Counting up from 5 to 7 must pass a number with a 1 in the highest red place and 0s below it, so every bit from the lowest up to that place is 0 in the answer. The lowest one can go.
421nowshiftleft101right111231answerboth shifted → 2 and 3, 1 bit dropped
left2
right3
shift1
Both numbers move one place right, so their lowest bit falls off (dashed). shift counts the dropped places, 1 so far, so the prefix can be put back later.
421nowshiftleft101right11123≠1answer2 and 3 differ → drop the lowest bit
left2
right3
The kept bits still differ (red). Counting up from 5 to 7 must pass a number with a 1 in the highest red place and 0s below it, so every bit from the lowest up to that place is 0 in the answer. The lowest one can go.
421nowshiftleft101right111112answerboth shifted → 1 and 1, 2 bits dropped
left1
right1
shift2
Both numbers move one place right, so their lowest bit falls off (dashed). shift counts the dropped places, 2 so far, so the prefix can be put back later.
421nowshiftleft101right11111=2answerboth are 1 → shared prefix found
left1
right1
The kept bits are now equal (green). Every number between 5 and 7 starts with these same bits, so each of them survives the AND.
421nowshiftleft101right111112answer100=4answer: 4
answer4
Shift the prefix back 2 places. The dropped places come back as 0s (blue), one for each bit some number in the range cleared. The AND of 5 to 7 is 4.
05

Clear the lowest 1 of right

right & (right - 1) removes the lowest 1-bit of right. Repeat it while right is still above left. Each removed bit lies below the common prefix, because the prefix with zeros after it is never above left, so the loop stops on exactly that value.

▶1class Solution:
▶2 def rangeBitwiseAnd(self, left: int, right: int) -> int:
▶3 while right > left:
▶4 right &= right - 1
▶5 return right
06

Common pitfalls

Looping over every number in the range

✗ Wrong
ans = left
for x in range(left + 1, right + 1):
    ans &= x
✓ Right
while left != right:
    left >>= 1
    right >>= 1
    shift += 1

On left = 1, right = 2147483647 the loop runs over two billion times and times out. In C++ or Java, for (int i = left; i <= right; i++) is worse: when right is the largest int, i wraps around to a negative number and the loop never ends.

Returning left & right

✗ Wrong
return left & right
✓ Right
return left << shift

It checks only the two ends, but the numbers between them can clear more bits. On left = 5, right = 7, 5 & 7 is 5 (binary 101), yet 6 (binary 110) is in the range and clears the last bit, so the answer is 4.

Returning the prefix without shifting it back

✗ Wrong
return left
✓ Right
return left << shift

After the loop the prefix still sits at the bottom of the number. On left = 5, right = 7 the loop stops at 1 after two shifts, so the code returns 1 instead of 4.

07

Edge cases

left equals right

The range holds one number, the loop runs zero times, and left << 0 returns it unchanged: left = right = 6 gives 6.

left is 0

0 is in the range and has no 1-bits, so the answer is 0. The loop shifts until right also reaches 0, then returns 0 << shift, which is 0.

08

Complexity

Time
O(log right)
Space
O(1)
Each pass drops one bit, and a number below 2³¹ has at most 31 bits, so the loop runs at most 31 times however wide the range is.
09

Bitwise AND of Numbers Range FAQ

Why does a range that crosses a power of two always give 0?

If left is below 2^k and right is at least 2^k, then 2^k − 1 (all 1s below bit k) and 2^k (a single 1 at bit k) are both in the range. They share no 1-bits, so their AND is 0 already. For example, left = 3, right = 4 gives 0.

Does the same prefix trick work for OR or XOR over a range?

No. A bit that changes inside the range is 0 in an AND but 1 in an OR, so the OR of a range is the common prefix followed by all 1s. XOR needs a different idea entirely, based on the pattern of 0 ^ 1 ^ … ^ n repeating every four numbers.