26. AND In Range
β GFG solution to the AND In Range problem: find bitwise AND of all numbers in range [l, r] using efficient bit manipulation techniques. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given two integers l and r. Find the result after applying the series of Bitwise AND ( & ) operation on every natural number between the range l to r (including both).
The bitwise AND operation compares each bit of two numbers and returns 1 only if both bits are 1. When we perform AND on a series of consecutive numbers, the result preserves only the common high-order bits (the common binary prefix) while all differing lower-order bits become 0.
π Examples
Example 1
Input: l = 8, r = 13
Output: 8
Explanation:
8 AND 9 AND 10 AND 11 AND 12 AND 13 = 8.
Binary: 1000 & 1001 & 1010 & 1011 & 1100 & 1101 = 1000 (which is 8)Example 2
Input: l = 2, r = 3
Output: 2
Explanation:
2 AND 3 = 2.
Binary: 10 & 11 = 10 (which is 2)π Constraints
$1 \le l \le r \le 10^9$
β
My Approach
The optimal approach uses Brian Kernighan's Algorithm to efficiently find the common binary prefix of all numbers in the range:
Brian Kernighan's Bit Clearing
Understanding the Pattern:
When performing AND on consecutive numbers, bits from right to left start differing.
The result is the common prefix of bits shared by all numbers in range.
Example: For [12,13,14,15], binary is [1100, 1101, 1110, 1111] β common prefix is 1100.
Algorithm:
Use Brian Kernighan's technique:
r &= (r - 1)clears the rightmost set bit.Keep clearing bits from
runtilrbecomes less than or equal tol.This efficiently removes all differing bits from right side.
Why It Works:
r & (r-1)removes the rightmost 1-bit from r.In a range [l, r], all bits that differ between l and r will eventually be cleared.
The remaining value is the common prefix - our answer.
Optimization:
Each iteration removes one differing bit from right.
Loop terminates when all differing bits are cleared.
Result is the largest number β€ r that can be formed using only common prefix bits.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(log(r - l)), where the loop runs proportional to the number of differing bits between l and r. In the worst case, this is O(log n) where n is the maximum value of r. The algorithm clears one bit per iteration until r becomes less than or equal to l.
Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space for variables l and r, with no extra data structures required.
π§βπ» Code (C++)
β Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated