◀ THE GRIND — BIT MANIPULATION

Minimum Array End

The drill: Build the smallest possible last element of a strictly increasing array of n positive integers whose bitwise AND all comes out to x — every entry has to carry all of x's bits and nothing forces the rest.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

Two positive integers arrive: n, a count, and x, a bit pattern every element of a hidden array must respect. The array holds exactly n distinct positive integers in strictly increasing order, and ANDing all of them together must equal x exactly.

Among every array that satisfies those rules, the task is to report the smallest possible value its last, largest element could take.

Every element must carry all of x's set bits, since an AND can never gain a bit that even one element lacks — but the positions where x is 0 are unconstrained and free to differ between elements, as long as the array keeps increasing strictly.

EX 01
n = 1 · x = 4
4
N = 1, THE ARRAY IS JUST [X]
EX 02
n = 2 · x = 7
15
X ALREADY HAS EVERY LOW BIT SET, SO THE FREE SLOT IS HIGHER UP
EX 03
n = 3 · x = 2
6
SEVERAL FREE BIT POSITIONS BELOW AND ABOVE X'S BIT
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

Simulating the array by hand — starting at x, always stepping up to the next number that still carries every bit of x — finds the right answer, but the count n can be enormous.

HINT 2 THE STRUCTURE

Every element only needs to agree with x on the bits x already has set; the bit positions where x is 0 are completely free to vary between elements and still keep the AND correct.

HINT 3 ONE STEP FROM THE ANSWER

Treat n − 1 in binary and pour its bits, one by one from the lowest, into x's zero-bit slots, skipping any position x already occupies. What's left is the minimum last element.

COACH'S BOARD — THE PATTERN, STEP BY STEP
BITS INTO THE GAPSPATTERN · SPREAD BITS INTO GAPSn = 3 · x = 2
4
2
1
X / N-1 / RESULT (BINARY)
x2 (010)
n-12 (10)
result2 (010)
STEP 1

x=2 already owns bit position 1, the 2's place — that bit is frozen. n−1 = 2 (binary 10) pours its own bits into the free slots, lowest gap first.

STEP 1 / 5 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/minimum-array-end.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def minEnd(self, n: int, x: int) -> int:
        n -= 1
        result = x
        bit = 0
        while n:
            while result & (1 << bit):  # skip bit positions x already occupies
                bit += 1
            if n & 1:
                result |= 1 << bit
            bit += 1
            n >>= 1
        return result
TIME O(LOG N + LOG X)SPACE O(1)PYTHON · RACE PACE · 13 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED