Copy set bits in a range

Pattern: Set, clear and toggle

medium

Build a mask with ones in positions l to r. y & mask keeps only y's set bits in that range, and OR-ing them into x switches those bits on in x, leaving everything else unchanged.

The problem

Given two numbers x and y and a range of bit positions l to r (counting from 1 at the right), copy every set bit of y in that range into x: those bits become 1 in x. Bits of x outside the range, and bits that are 0 in y, stay as they are. Return the new x. For example, x = 10, y = 13, l = 2, r = 3 gives 14, and x = 8, y = 7, l = 1, r = 2 gives 11.

The link above is a GeeksforGeeks article. The function name copySetBits is this guide's own.

Think first

  • Which mask has ones exactly in positions l to r?
  • How do you keep only y's bits in that range?
  • Which operator switches bits on without switching any off?

Hints

    Brute force, and why it fails

    Loop over positions l..r, and set bit i of x when bit i of y is set: O(r - l). The mask does it in O(1).

    The key insight

    A mask turns "only in this range" into one AND, and "switch on" into one OR.

    Dry run

    x = 1 0 1 00 
    y = 1 1 0 11 

    x = 10 (1010), y = 13 (1101), l = 2 and r = 3. Positions count from 1 at the right.

    Step 1 of 4

    The plan

    mask = ((1 << (r - l + 1)) - 1) << (l - 1)
    return x | (y & mask)
    

    Complexity

    Time
    O(1)
    Space
    O(1)

    A few bit operations.

    Edge cases

    • l = r: one bit.
    • The full range 1..31: use a 64-bit shift to build the mask.
    • y with no set bits in the range: x is unchanged.
    I've built my logic, show the code

    Java

    class Solution {
        public int copySetBits(int x, int y, int l, int r) {
            int width = r - l + 1;
            int mask = (int) (((1L << width) - 1) << (l - 1));   // ones in positions l..r (1-based from the right)
            return x | (y & mask);                  // keep x, and switch on y's set bits inside the range
        }
    }

    C++

    class Solution {
    public:
        int copySetBits(int x, int y, int l, int r) {
            int width = r - l + 1;
            int mask = static_cast<int>(((1LL << width) - 1) << (l - 1));   // ones in positions l..r (1-based)
            return x | (y & mask);                  // keep x, and switch on y's set bits inside the range
        }
    };

    Python

    class Solution:
        def copySetBits(self, x: int, y: int, l: int, r: int) -> int:
            mask = ((1 << (r - l + 1)) - 1) << (l - 1)   # ones in positions l..r (1-based from the right)
            return x | (y & mask)                   # keep x, and switch on y's set bits inside the range

    Common mistakes

    • Counting positions from 0.
    • Using XOR, which would clear bits already set in x.
    • Building (1 << 32) - 1 in 32 bits, which overflows.

    Similar problems