3394. Minimum Array End
My accepted Python solution to LeetCode problem 3394, Minimum Array End, running in 0ms.
- Difficulty: Medium
- Python
- Runtime 0ms
- Memory 17.4MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 0ms, memory 17.4MB, accepted 2025-12-29.
class Solution:
def minEnd(self, n: int, x: int) -> int:
# Key insight: We need n elements with AND = x
# All elements must have all bits of x set
# The minimum last element is achieved by filling in only the 0-bits of x
# We essentially "insert" the binary representation of (n-1) into the 0-bit positions of x
# Time: O(64) = O(1), Space: O(1)
result = x
n -= 1 # We need to add n-1 more unique numbers after x
bit_pos = 0
while n > 0:
# Find the next 0 bit in x
while (result >> bit_pos) & 1:
bit_pos += 1
# Set this bit according to the current bit of (n-1)
if n & 1:
result |= (1 << bit_pos)
n >>= 1
bit_pos += 1
return result