Bitwise AND of Numbers Range - Problem
You're given two integers left and right that define a range [left, right]. Your task is to find the bitwise AND of all numbers in this range, inclusive.

The bitwise AND operation compares each bit position of the numbers and returns 1 only if all numbers have 1 in that position. For example, if we have range [5, 7], we need to compute 5 & 6 & 7.

Key Challenge: The range could be very large (up to 231 - 1), so iterating through every number would be too slow! You need to find a clever bit manipulation approach.

Example: For range [5, 7]:
• 5 = 101₂
• 6 = 110₂
• 7 = 111₂
• 5 & 6 & 7 = 100₂ = 4

Input & Output

example_1.py — Basic Range
$ Input: left = 5, right = 7
Output: 4
💡 Note: The bitwise AND of 5 & 6 & 7 is 4. In binary: 101₂ & 110₂ & 111₂ = 100₂ = 4. Only the bit at position 2 remains 1 across all numbers.
example_2.py — Large Range
$ Input: left = 0, right = 0
Output: 0
💡 Note: When left equals right, the result is simply that number. 0 & 0 = 0.
example_3.py — Power of 2 Range
$ Input: left = 1, right = 2147483647
Output: 0
💡 Note: In such a large range, all bit positions will have both 0s and 1s appearing, so the final AND result is 0. This demonstrates why the optimal approach is necessary.

Constraints

  • 0 ≤ left ≤ right ≤ 231 - 1
  • Range can be very large - brute force will timeout
  • Both left and right are inclusive in the range

Visualization

Tap to expand
Bitwise AND Range Pattern VisualizationRange [5, 7] Binary Analysis:5: 101₂ 6: 110₂ 7: 111₂Bit Position Analysis:Position 2 (MSB)5: 1, 6: 1, 7: 1✓ All same → 1Position 15: 0, 6: 1, 7: 1✗ Different → 0Position 0 (LSB)5: 1, 6: 0, 7: 1✗ Different → 0Common Prefix Method:Step 1: Compare left=5 and right=7left = 101₂, right = 111₂Step 2: Find first different bit (position 1)Step 3: Keep common prefix '1' + zeros → 100₂ = 4Result: 4 (Binary: 100₂)Only the common prefix bit survives!
Understanding the Visualization
1
Bit Cycling
In any range, rightmost bits cycle through 0 and 1
2
AND Effect
When ANDing cycling bits, result becomes 0
3
Common Prefix
Only stable prefix bits survive the AND operation
4
Pattern Recognition
Find where left and right first differ
Key Takeaway
🎯 Key Insight: In any range, only the common binary prefix of the boundaries survives the AND operation. Once bits start differing, all subsequent positions become 0.
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 28
78.2K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen