#201

Bitwise AND of Numbers Range

Medium
Bit ManipulationBit ManipulationBinary Representation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(log(max))
Space
O(1)
O(1)
💡

Intuition

Time O(log(max))Space O(1)

The optimal solution leverages the properties of binary numbers. The bitwise AND of a range will only preserve bits that are the same for all numbers in that range. We can find the common prefix of 'left' and 'right' to determine the result efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a variable 'shift' to 0.
  2. 2Step 2: While 'left' is not equal to 'right', shift both left and right to the right by 1 bit and increment 'shift'.
  3. 3Step 3: After the loop, shift 'left' back to the left by 'shift' bits to get the final result.
solution.py9 lines
1# Full working Python code
2
3def rangeBitwiseAnd(left, right):
4    shift = 0
5    while left < right:
6        left >>= 1
7        right >>= 1
8        shift += 1
9    return left << shift

Complexity note: The time complexity is O(log(max)) because we are shifting bits, which takes logarithmic time relative to the size of the numbers. The space complexity is O(1) since we only use a constant amount of space.

  • 1The bitwise AND operation only retains bits that are set in all numbers.
  • 2The common prefix of the binary representations of 'left' and 'right' determines the result.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.