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++)
β‘ View Alternative Approaches with Code and Analysis
π 2οΈβ£ Bit Shifting Approach
π‘ Algorithm Steps:
Continue right shifting both numbers until they become equal.
Count the number of shifts performed during this process.
Left shift the result back by the same count.
This finds the common prefix of bits in binary representation.
π Complexity Analysis:
Time: β±οΈ O(log n) - Based on number of bits
Auxiliary Space: πΎ O(1) - Constant space usage
β
Why This Approach?
Clear logic based on common bit prefix
Easy to understand and visualize
Standard approach for range AND problems
π 3οΈβ£ XOR-Based Approach
π‘ Algorithm Steps:
Find XOR of l and r to identify differing bits.
Find the position of most significant bit in XOR result.
Create a mask to clear all bits from that position onwards.
Apply mask to either l or r to get the common prefix.
π Complexity Analysis:
Time: β±οΈ O(log n) - Iterating through bits
Auxiliary Space: πΎ O(1) - Only using constants
β
Why This Approach?
Uses XOR to identify bit differences
Mathematical approach to find common prefix
Good for understanding bit manipulation
π 4οΈβ£ Alternative Kernighan's Algorithm
π‘ Algorithm Steps:
Use two's complement property:
r & -risolates the rightmost set bit.Subtract this isolated bit from r to clear it.
Continue until r becomes less than or equal to l.
This achieves the same result as
r &= (r-1)but uses different bit manipulation.
π Complexity Analysis:
Time: β±οΈ O(log n) - Number of set bits to clear
Auxiliary Space: πΎ O(1) - Constant space
β
Why This Approach?
Very concise implementation
Uses two's complement bit trick
Alternative formulation of bit clearing
π 5οΈβ£ Most Significant Bit Approach
π‘ Algorithm Steps:
Find the position where l and r first differ in their binary representation.
Calculate the common prefix length by comparing bits from left to right.
Create a mask with all 1s up to the common prefix length.
Apply this mask to l (or r) to extract the common prefix.
π Complexity Analysis:
Time: β±οΈ O(log n) - Finding differing bit position
Auxiliary Space: πΎ O(1) - Constant space
β
Why This Approach?
Direct approach to find common prefix
Clear separation of finding and reconstructing prefix
Good for educational purposes
π π Comparison of Approaches
π Approach
β±οΈ Time Complexity
πΎ Space Complexity
β Pros
β οΈ Cons
π·οΈ Brian Kernighan (r&=r-1)
π’ O(log n)
π’ O(1)
π Shortest code
π§ Less intuitive logic
π Bit Shifting
π’ O(log n)
π’ O(1)
π Clear and intuitive
π Slightly more code
π XOR-Based
π’ O(log n)
π’ O(1)
π― Mathematical insight
π More operations required
π Alternative Kernighan
π’ O(log n)
π’ O(1)
β Very concise
π§ Uses two's complement
π― MSB Approach
π’ O(log n)
π’ O(1)
π Educational value
π More explicit logic
π Best Choice Recommendation
π― Scenario
ποΈ Recommended Approach
π₯ Performance Rating
π Shortest code needed
π₯ Brian Kernighan (r&=r-1)
β β β β β
π Readability priority
π₯ Bit Shifting
β β β β β
π§ Interview explanation
π₯ Bit Shifting
β β β β β
π― Competitive Programming
π Brian Kernighan
β β β β β
π Learning bit manipulation
ποΈ XOR-Based
β β β β β
β 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