Bitwise AND of Numbers Range (LeetCode 201): Solution and Explanation
Given two integers left and right, return the result of AND-ing together every integer from left to right inclusive. The range can span up to about two billion numbers, so looping over it is not an option.
Watch it run step by step
Try your own input and write the code →Intuition
The direct approach ANDs every number in the range. It is correct but can run two billion iterations, and it is wasteful because the answer collapses to zero very quickly in most bit positions. The real question is which bits survive.
A bit survives the AND only if it is 1 in every number of the range. Consider any bit position where left and right differ. Somewhere between them the counter must roll over at that position, so some number in the range has a 0 there, and the same is true of every lower bit, because a rollover at a higher position passes through a number whose lower bits are all 0. So every bit at or below the highest differing position is wiped out.
What survives is exactly the common binary prefix of left and right, the leading bits they share, followed by zeros. The code finds that prefix by shifting both numbers right one bit at a time until they become equal, counting the shifts. Shifting the common value back left by that count restores the prefix in its original position with zeros underneath. For example, 12 and 15 are 1100 and 1111. They share the prefix 11, they differ in the lower two bits, and the AND of 12, 13, 14 and 15 is 1100, which is 12. Notice that the size of the range alone tells you a lot: once the range covers more than 2^k numbers, the lowest k bits must all be zero.
Approach: Common binary prefix by shifting
- Set
shift = 0. - While
left < right, shift both right by one bit and incrementshift. Each shift discards one low bit that cannot survive. - When the loop ends,
leftequalsright, and that value is the shared prefix. - Return
left << shift, which puts the prefix back in place and fills the dropped positions with zeros.
Step-by-step example
left = 5, right = 7
- In binary,
left = 101andright = 111. They differ, so shift:left = 10,right = 11,shift = 1. - Still different, so shift again:
left = 1,right = 1,shift = 2. - Now they are equal and the loop stops. The common prefix is
1. - Return
1 << 2 = 100, which is 4. Checking directly,5 & 6 & 7 = 101 & 110 & 111 = 100, also 4.
Code: Python, Java, C++
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 << shift1class Solution {
2 public int rangeBitwiseAnd(int left, int right) {
3 int shift = 0;
4 while (left < right) {
5 left >>= 1;
6 right >>= 1;
7 shift++;
8 }
9 return left << shift;
10 }
11}1class Solution {
2public:
3 int rangeBitwiseAnd(int left, int right) {
4 int shift = 0;
5 while (left < right) {
6 left >>= 1;
7 right >>= 1;
8 shift++;
9 }
10 return left << shift;
11 }
12};Time and space complexity
O(log n)
Each iteration removes one bit, so the loop runs at most as many times as there are bits in right, which is 31 for the given limits. In practice that is constant time.
O(1)
Only the two inputs and a shift counter are used.
Other approaches
Clear lowest set bit of right (time O(log n), space O(1))
Repeat right &= right - 1 while right > left. Each step clears the lowest 1 bit of right, and the loop stops once right drops to the common prefix. It often runs fewer iterations than shifting.
Brute-force AND over the range (time O(right - left), space O(1))
AND every number from left to right, with an early exit if the result reaches 0. It is easy to write but can be linear in the size of the range.
Common mistakes
- Looping over the whole range. Even with early exit, ranges like
[2^30, 2^31 - 1]keep a nonzero result for a long time and time out. - Shifting only
rightor onlyleft. Both must lose the same low bits so they can be compared on equal footing. - Forgetting to shift the prefix back left at the end and returning
leftas is, which gives a number that is far too small. - Assuming the answer is
left & right. That ignores the numbers in between; for 5 and 7 it gives 5, but 6 clears the lowest bit.
Frequently asked questions
Why is the answer the common prefix of left and right?
Below the highest bit where they differ, the range must pass through a number with that bit and every lower bit set to 0, so all those positions are 0 in the AND. Bits above that point are identical across the whole range and survive.
What is the time complexity of bitwise AND of numbers range?
O(log n), the number of bits in right, because each loop iteration removes one bit. With 32-bit inputs that is at most 31 iterations.
What is the trick with n & (n - 1)?
n & (n - 1) clears the lowest set bit of n. Applying it to right repeatedly until it is no longer above left also yields the common prefix.
What if left equals right?
The loop never runs and the function returns left unchanged, which is correct because the range contains one number.