Bitwise AND of Numbers Range

MediumBit Manipulation · Common Prefix🧩 Bit ManipulationLeetCode #201 ↗Updated

Problem

Given two integers left ≤ right, compute left & (left+1) & … & right — the bitwise AND of every integer in the closed range. The range can contain about two billion numbers, so walking it one by one is not an option.
Inputleft = 5, right = 7Output4
Inputleft = 0, right = 0Output0
Inputleft = 1, right = 2147483647Output0

0 ≤ left ≤ right ≤ 231 − 1

Try it yourself

Java
class Solution {
    public int rangeBitwiseAnd(int left, int right) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Counting from left to right flips every bit below the highest position where they differ, so those bits all become 0. The answer is the common binary prefix of left and right, padded with zeros.
PatternBit Manipulation

Instinct Pairs that cancel, counting 1s, powers of two, subsets as numbers, or 'no + or - allowed' - drop to binary and use XOR, AND, OR and shifts.

Memory hack XOR is a forgetful twin detector - see something twice and it vanishes; n & (n-1) snips off the last lit bulb.

Open the Bit Manipulation guide →

Approaches

Brute ForceAND Every Number

Time O(right − left)Space O(1)

Start from left and AND in each following number. Once the result hits 0 nothing can turn a bit back on, so stop early. Use a long counter so right = 231−1 doesn’t overflow the loop.

Java
public int rangeBitwiseAnd(int left, int right) {
    int result = left;
    // long counter: x++ past Integer.MAX_VALUE would overflow
    for (long x = (long) left + 1; x <= right && result != 0; x++) {
        result &= (int) x;
    }
    return result;
}

Fine for tiny ranges; up to ~2·109 steps when the result stays non-zero.

At a glance

LevelApproachTimeSpace
Brute ForceAND Every NumberO(right − left)O(1)
BetterDecide Each Bit IndependentlyO(log right)O(1)
OptimalStrip Low Bits of right (Common Prefix)O(log right)O(1)
Common pitfalls
  • Looping with an int counter up to Integer.MAX_VALUE — infinite loop on overflow.
  • Assuming the answer is left & right — wrong for 5..7 (gives 5, not 4).
  • Iterating the range without an early exit — billions of steps.
Interview tips
  • Write 5, 6, 7 in binary and let the interviewer see the low bits flip.
  • State the claim: answer = common prefix of left and right.
  • Mention both prefix extractions: shifting and n & (n − 1).
Pattern
Common binary prefix → AND/OR over a consecutive integer range collapses to the shared high bits.
My notes saved in this browser