Skip to main content

Minimum Array End

Medium
Data Structures and Algorithms
Editorial
Topics:
Bit Manipulation
Array
Math

Implement Solution.minEnd(n, x) to determine the smallest possible final value of an array of n positive integers.

The array must begin with x, must be strictly increasing, and the bitwise AND of every element must equal x. Bitwise AND compares corresponding binary bits and keeps a bit set only when it is set in every operand.

Return the minimum value that can appear at the last index of such an array. Return only this integer; the array itself does not need to be constructed.

Example 1:

Input: n = 1, x = 13
Output: 13
Explanation: With one element, the array is simply [13], so its final value is 13.

Example 2:

Input: n = 4, x = 10
Output: 15
Explanation: The smallest valid sequence ends with 15; its elements can be 10, 11, 14, and 15, whose bitwise AND is 10.

Example 3:

Input: n = 5, x = 6
Output: 22
Explanation: The zero bits available in 6 are filled in increasing binary order, producing a minimum final value of 22 for five elements.

Constraints:

  • ``n is an integer.
  • ``x is an integer.
  • 1 <= n, x <= 10^4.
  • The answer fits in a 32-bit signed integer.

Need help or want more practice?

Practise in an interviewGet AI Coach help