AlgoInsight

DSA problem

Bitwise AND of Numbers Range

MediumBit ManipulationPattern: Bit Manipulationtop300AmazonGoogleBloomberg

Given two integers left and right that represent the inclusive range [left, right], return the bitwise AND of all numbers in this range.

Computing the AND by iterating over every number would be far too slow when the range is large. The key observation is that the bitwise AND of a contiguous range equals the common binary prefix shared by left and right, with all trailing bits set to zero.

Intuitively, any bit position that changes at least once across the range will be 0 for some number, forcing the AND of that position to 0. Only the leading bits that are identical in both left and right (and therefore in every number between them) survive.

So the answer is found by stripping away the differing low-order bits until left and right become equal; the resulting common value, shifted back into place, is the result.

Examples

Example 1
Input: left = 5, right = 7
Output: 4
Explanation: The range is 5 (101), 6 (110), 7 (111). The AND of 101, 110, and 111 is 100, which equals 4.
Example 2
Input: left = 0, right = 0
Output: 0
Explanation: The range contains only 0, so the AND is 0.
Example 3
Input: left = 1, right = 2147483647
Output: 0
Explanation: The range spans many values where every bit position changes, so the bitwise AND collapses to 0.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

bit-manipulation

Browse all DSA problems