Minimum Array End - Problem

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]
  • The result of the bitwise AND operation between all elements of nums is x

Return the minimum possible value of nums[n - 1].

Input & Output

Example 1 — Basic Case
$ Input: n = 3, x = 4
Output: 6
💡 Note: Array [4,5,6] has AND = 4 & 5 & 6 = 4, strictly increasing, minimum last element is 6
Example 2 — Single Element
$ Input: n = 1, x = 2
Output: 2
💡 Note: Array [2] has AND = 2, only one element so result is 2
Example 3 — Larger Case
$ Input: n = 4, x = 1
Output: 7
💡 Note: Array [1,3,5,7] has AND = 1 & 3 & 5 & 7 = 1, strictly increasing, minimum last element is 7

Constraints

  • 1 ≤ n ≤ 108
  • 1 ≤ x ≤ 108

Visualization

Tap to expand
Minimum Array End - Optimal Solution INPUT n = 3 array size x = 4 AND result Binary of x = 4: 1 0 0 2^2 2^1 2^0 Goal: Build array where AND of all = 4 and nums[n-1] is MIN Constraints: - Strictly increasing - AND result must be x ALGORITHM STEPS 1 Start with x First element = 4 (100) 2 Fill zero bits Use (n-1) in free positions 3 Bit manipulation n-1 = 2 = (10) binary 4 Merge bits Insert into x's zero spots Bit Distribution: x=4: 1 0 0 ^ ^ ^ | fill with fixed (n-1) bits FINAL RESULT Constructed Array: 4 5 6 Binary Verification: 4 = 100 5 = 101 6 = 110 -------- AND = 100 = 4 [OK] Output: 6 nums[n-1] = 6 Key Insight: To preserve AND = x, all elements must have x's set bits. The minimum last element is found by encoding (n-1) into the zero-bit positions of x. This ensures strictly increasing values while keeping the AND result intact. Time: O(log n), Space: O(1). TutorialsPoint - Minimum Array End | Optimal Bit Manipulation Approach
Asked in
Microsoft 25 Google 20
28.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen