Minimum Array End Problem
Description
LeetCode Problem 3133.
You are given two integers n and x. You have to construct an array of positive integers nums of size n where for every 0 <= i < n - 1, nums[i + 1] is greater than nums[i], and the result of the bitwise AND operation between all elements of nums is x.
Return the minimum possible value of nums[n - 1].
Example 1:
Input: n = 3, x = 4
Output: 6
Explanation:
nums can be [4,5,6] and its last element is 6.
Example 2:
Input: n = 2, x = 7
Output: 15
Explanation:
nums can be [7,15] and its last element is 15.
Constraints:
1 <= n, x <= 10^8
Solution
Approach: Greedy + Bit Manipulation
The AND of all elements must be x, so every element contains all the set bits of x, and the smallest array starts at x itself. Each next element is the next larger number that still contains those bits.
Ignore the positions of the set bits of x: the remaining (zero) positions then count 0, 1, 2, 3, ... in binary. So the n-th element is obtained by writing the bits of n - 1 into the zero positions of x, from the lowest one upward. That is the minimum possible last element.
Complexity: time O(log x + log n), space O(1).
class Solution:
def minEnd(self, n: int, x: int) -> int:
n -= 1
ans = x
for i in range(31):
if x >> i & 1 ^ 1:
ans |= (n & 1) << i
n >>= 1
ans |= n << 31
return ans