Bitwise AND of Numbers Range

Medium

Topics
Bit Manipulation

Given two integers a and b with a <= b, return the bitwise AND of all numbers in the inclusive range [a, b].

Example 1

43210left = 500101right = 700111AND00100
ANDing a whole range zeroes any bit that changes anywhere inside it, so only the common leading prefix of the two endpoints survives — shaded above. No iteration over the range is needed; the answer is 4.
Cells are the binary expansion, most significant bit on the left; the small numbers are bit positions.
Input:  a = 5, b = 7
Output: 4

Example 2

43210left = 000000right = 000000AND00000
Input:  a = 0, b = 0
Output: 0

Example 3

43210left = 2611010right = 3011110AND11000
Input:  a = 26, b = 30
Output: 24

Constraints

  • 0 <= a <= b <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls

Intuition

AND-ing a whole range can only keep a bit that is set in every number of the range. Walk the bits from the top: the high bits where a and b already agree are constant across the range, and everything below the first disagreement must be zero.

Why the low bits vanish: if a and b differ at bit k, the range spans a point where bit k flips, and crossing it forces every bit below k through a zero. So the answer is the common binary prefix of a and b, padded with zeros — which is exactly what shifting both right until they meet and shifting back computes.

Approach

  1. Shift a and b right together, counting the shifts, until they are equal.
  2. That shared value is the common prefix.
  3. Shift it back left by the count.

Dry Run

a = 5 (0b101)   b = 7 (0b111)

  a      b      binary a   binary b
  5      7      101        111        differ -- shift
  2      3      10         11         differ -- shift
  1      1      1          1          equal  -- common prefix is 1, after 2 shifts

answer 1 << 2 = 4

spot checks against brute force
  [5, 7]                     -> 4
  [0, 0]                     -> 0
  [2147483646, 2147483647]   -> 2147483646
  [1, 2147483647]            -> 0

Complexity

  • Time — O(log b): at most 31 shifts at the stated bound, since each iteration drops a bit.
  • Space — O(1).

Common Pitfalls

  • Looping over the range and AND-ing. The range reaches 2³&sup9; values, so this is not a slow solution, it is a non-terminating one.
  • Returning a & b. That keeps bits the endpoints happen to share, but a bit can be set at both ends and clear in between — [5,7] gives 5 & 7 = 5, while the true answer is 4.
  • Shifting only one of the two operands, which loses the alignment that makes the prefix meaningful.
  • Forgetting the a == 0 case. It needs no special handling — the loop shifts b down to 0 and returns 0 — but say so rather than adding a branch.
  • Using a signed right shift on a value near 2³&sup9;-1 in a language where the top bit matters. The constraints keep everything non-negative, so a logical shift and an arithmetic shift agree here; on the full 32-bit range they would not.

Full Solution — all languages

class Solution:
    def rangeBitwiseAnd(self, a, b):
        shift = 0
        while a < b:
            a >>= 1
            b >>= 1
            shift += 1
        return a << shift
SensAI
Beta
Tap the mic to stop voice mode