SDE & MLE Prep

3133. Minimum Array End

Problem

Build a strictly increasing array of n positive integers whose bitwise AND is exactly x. Return the smallest possible value of its last element.

Example: n = 3, x = 4 → 6 ([4,5,6]); n = 2, x = 7 → 15

Constraints: n, x ≤ 10⁸.

Every element must contain all of x's set bits, so elements are x with some of its zero bits filled in. The n-th smallest such number puts the binary digits of n − 1 into x's zero-bit positions (low to high) — "deposit" n − 1 into the free bits.

x = 4      = 0b100   free bits: positions 0, 1, 3, 4, ...
n = 3 -> n-1 = 0b10  -> bit 0 <- 0, bit 1 <- 1   -> 0b110 = 6     (array 4, 5, 6)

Complexity: O(log n + log x).

class Solution:
    def minEnd(self, n: int, x: int) -> int:
        res, k, bit = x, n - 1, 1
        while k:
            if not x & bit:              # free position: place the next bit of n - 1
                if k & 1:
                    res |= bit
                k >>= 1
            bit <<= 1
        return res