Lexicographically Smallest Negated Permutation that Sums to Target Problem
Description
LeetCode Problem 3752.
You are given a positive integer n and an integer target.
Return the lexicographically smallest array of integers of size n such that:
- The sum of its elements equals
target. - The absolute values of its elements form a permutation of size
n.
If no such array exists, return an empty array.
A permutation of size n is a rearrangement of integers 1, 2, ..., n.
Example 1:
Input: n = 3, target = 0
Output: [-3,1,2]
Explanation:
The arrays that sum to 0 and whose absolute values form a permutation of size 3 are:
- [-3, 1, 2]
- [-3, 2, 1]
- [-2, -1, 3]
- [-2, 3, -1]
- [-1, -2, 3]
- [-1, 3, -2]
- [1, -3, 2]
- [1, 2, -3]
- [2, -3, 1]
- [2, 1, -3]
- [3, -2, -1]
- [3, -1, -2]
The lexicographically smallest one is [-3, 1, 2].
Example 2:
Input: n = 1, target = 10000000000
Output: []
Explanation:
There are no arrays that sum to 10000000000 and whose absolute values form a permutation of size 1. Therefore, the answer is [].
Constraints:
1 <= n <= 10^5-10^10 <= target <= 10^10
Solution
Approach: Greedy
If every number from 1 to n were positive, the sum would be S = n(n+1)/2. Turning a number x negative lowers the sum by 2x, so we need S - target to be non-negative and even. Then the numbers we negate must add up to need = (S - target) / 2.
To make the array lexicographically smallest, we want the most negative values first, so we negate the largest numbers: go from n down to 1 and negate x whenever need >= x, subtracting it from need. Every sum between 0 and S can be built from distinct numbers in 1..n, and this greedy choice always reaches it exactly.
Finally output the negated numbers (largest magnitude first), followed by the remaining positive numbers in increasing order. If S - target is negative, odd, or larger than 2S (the sum with every number negated is -S), return an empty array.
Complexity: O(n) time and O(n) space for the answer.
class Solution:
def lexSmallestNegatedPerm(self, n: int, target: int) -> List[int]:
total = n * (n + 1) // 2
diff = total - target
if diff < 0 or diff % 2 or diff // 2 > total:
return []
need = diff // 2 # sum of the numbers that get a minus sign
neg = []
for x in range(n, 0, -1):
if need >= x:
need -= x
neg.append(-x)
# every sum in [0, total] is reachable, so need is 0 here
neg_set = set(-v for v in neg)
pos = [x for x in range(1, n + 1) if x not in neg_set]
return neg + pos