Shubham Sourabhthe room · director's cutplain résumé
Room 04 · The Grind — Bit Manipulation

Bitwise AND of Numbers Range

MEDIUM✓ CHIP-TIMEDLC #201 — FULL STATEMENT

The briefingthe full drill, in my own words

The drill: AND together every integer in the inclusive range from left to right — one differing bit anywhere in that range zeroes it out for good, so the answer is usually shorter than you'd guess.

Two integers arrive marking the two ends of an inclusive range, with left never larger than right, and the task is to AND together every integer from left through right.

Because a bitwise AND only keeps a bit that every single operand agrees on, the moment any two numbers inside that range disagree on some bit position, that bit is gone from the final result for good.

The range can span a huge count of integers, but the answer only ever depends on the small handful of leading bits where left and right themselves still agree.

  • left and right are non-negative integers with left ≤ right
  • the range being ANDed is inclusive on both ends
  • values can run up into the billions, so the range itself may be enormous
  • the result depends only on the shared leading bits of left and right
EX 01
left = 5 · right = 7
→ 4
the board's example
EX 02
left = 0 · right = 0
→ 0
single value, zero
EX 03
left = 1 · right = 1
→ 1
single value, nonzero

The hintstake only what you need

HINT 1 THE NUDGE

ANDing every number in a huge range one by one is correct, but the range itself can be enormous — most of that work produces zero long before the loop ends.

HINT 2 THE STRUCTURE

The moment two numbers in the range disagree on a bit, that bit is gone from the final answer forever. What's the earliest bit where left and right themselves could possibly disagree?

HINT 3 ONE STEP FROM THE ANSWER

Right-shift left and right together until they're equal — that surviving common prefix is the only part of the answer that could ever have stayed 1. Shift it back into place.

Coach's boardthe pattern, step by step

THE COMMON PREFIXPATTERN · COMMON PREFIX SHIFTleft = 5 · right = 7
4
2
1
LEFT / RIGHT (BINARY)
left → 5 (101)
right → 7 (111)
STEP 1

5 and 7 disagree on their lowest bit. Shift both right together until they match — the surviving prefix is the answer.

STEP 1 / 5 · ← → WORK TOO

The splitstwo paces, two languages

grind/bitwise-and-of-numbers-range.py — RACE PACE
LANG ▸
PACE ▸
class Solution:
    def rangeBitwiseAnd(self, left: int, right: int) -> int:
        shift = 0
        while left != right:
            left >>= 1
            right >>= 1
            shift += 1
        return left << shift
TIME O(LOG RIGHT)SPACE O(1)PYTHON · RACE PACE · 8 LN

✓ CHIP-TIMEDALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED