#3752

Lexicographically Smallest Negated Permutation that Sums to Target

Medium
ArrayMathTwo PointersGreedySortingGreedySorting
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(n)

Start with the sum of the first n natural numbers. Adjust the largest number to meet the target while ensuring the absolute values remain a permutation.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate S = n * (n + 1) / 2.
  2. 2Step 2: Check if target is within the bounds [-S, S] and if (S - target) is even.
  3. 3Step 3: Create the array [1, 2, ..., n] and adjust the largest element to match the target.
solution.py7 lines
1def smallest_permutation(n, target):
2    S = n * (n + 1) // 2
3    if target < -S or target > S or (S - target) % 2 != 0:
4        return []
5    arr = list(range(1, n + 1))
6    arr[-1] += target - S
7    return [-x if x == arr[-1] else x for x in arr]

Complexity note: Linear time to create the array and adjust the last element.

  • 1The sum of the first n natural numbers defines the limits for the target.
  • 2Adjusting the largest number allows for flexibility in achieving the target sum.

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