Bitwise AND of Numbers Range
MedPrompt
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: 4Example 2:
Input: left = 0, right = 0
Output: 0Example 3:
Input: left = 1, right = 2147483647
Output: 0
Constraints:
0 <= left <= right <= 231 - 1
Approaches
3 approaches with complexity analysis and trade-offs.
The most straightforward approach is to perform a bitwise AND operation on all numbers in the range [left, right] one by one.
Algorithm
- Initialize
resultwith the value ofleft - Iterate from
left + 1toright:- Update
result = result & current_number - If
resultbecomes 0, break the loop (optimization)
- Update
- Return
result
Walkthrough
In this approach, we iterate through all numbers from left to right and perform a bitwise AND operation on each number with the result of previous operations.
public int rangeBitwiseAnd(int left, int right) { int result = left; for (int i = left + 1; i <= right; i++) { result &= i; // If result becomes 0, any further AND operations will remain 0 if (result == 0) { break; } } return result;}This approach works correctly for small ranges, but it will time out for large ranges like [1, 2147483647] because we would need to perform billions of operations.
Complexity
Time
O(right - left) in the worst case
Space
O(1)
Trade-offs
Pros
Simple and easy to understand
Works well for small ranges
Cons
Very inefficient for large ranges
Will time out for inputs like [1, 2147483647]
Solutions
Solution
public class Solution { public int RangeBitwiseAnd(int left, int right) { while (left < right) { right &= (right - 1); } return right; }}Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.