#3133

Minimum Array End

Medium
Bit ManipulationBit ManipulationArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(1)
Space
O(1)
O(1)
💡

Intuition

Time O(1)Space O(1)

The optimal approach constructs the array directly by leveraging the properties of bitwise operations. We can merge x with increasing integers to ensure the AND condition is satisfied while keeping the last element minimal.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize an array nums of size n.
  2. 2Step 2: Set nums[0] = x, then fill the rest of the array with x + i for i from 1 to n - 1.
  3. 3Step 3: Ensure that each element is greater than the previous one, which is guaranteed by the construction.
solution.py5 lines
1# Full working Python code
2
3def min_array_end_optimal(n, x):
4    return x + n - 1
5

Complexity note: This approach runs in constant time and space since it directly computes the last element without any loops.

  • 1The bitwise AND operation retains bits only where both operands have bits set.
  • 2Constructing the array directly can save time by avoiding unnecessary checks.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.