githubEdit

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 Linkarrow-up-right

🧩 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

  1. 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.

  2. Algorithm:

    • Use Brian Kernighan's technique: r &= (r - 1) clears the rightmost set bit.

    • Keep clearing bits from r until r becomes less than or equal to l.

    • This efficiently removes all differing bits from right side.

  3. 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.

  4. 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++)

chevron-right⚑ View Alternative Approaches with Code and Analysishashtag

πŸ“Š 2️⃣ Bit Shifting Approach

πŸ’‘ Algorithm Steps:

  1. Continue right shifting both numbers until they become equal.

  2. Count the number of shifts performed during this process.

  3. Left shift the result back by the same count.

  4. 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:

  1. Find XOR of l and r to identify differing bits.

  2. Find the position of most significant bit in XOR result.

  3. Create a mask to clear all bits from that position onwards.

  4. 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:

  1. Use two's complement property: r & -r isolates the rightmost set bit.

  2. Subtract this isolated bit from r to clear it.

  3. Continue until r becomes less than or equal to l.

  4. 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:

  1. Find the position where l and r first differ in their binary representation.

  2. Calculate the common prefix length by comparing bits from left to right.

  3. Create a mask with all 1s up to the common prefix length.

  4. 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?arrow-up-right. Let's make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


πŸ“Visitor Count

Visitor counter

Last updated