Leetcode #201: Bitwise AND of Numbers Range
In this guide, we solve Leetcode #201 Bitwise AND of Numbers Range in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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 Constraints: 0 <= left <= right <= 231 - 1
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Bit Manipulation
Intuition
The problem structure lets us track state with bitwise operations.
Bit operations are constant time and avoid extra memory.
Approach
Apply XOR/AND/OR and shifts to maintain the required invariant.
Aggregate the result in a single pass.
Steps:
- Identify a bitwise invariant.
- Combine values with bit operations.
- Return the aggregated result.
Example
Input: left = 5, right = 7
Output: 4
Python Solution
class Solution:
def rangeBitwiseAnd(self, left: int, right: int) -> int:
while left < right:
right &= right - 1
return right
Complexity
The time complexity is O(n). The space complexity is O(1).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.