LeetCode #3752 — MEDIUM

Lexicographically Smallest Negated Permutation that Sums to Target

Move from brute-force thinking to an efficient approach using array strategy.

Solve on LeetCode
The Problem

Problem Statement

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 <= 105
  • -1010 <= target <= 1010
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: 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.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Array · Math · Two Pointers · Greedy

Example 1

3
0

Example 2

1
10000000000
Step 02

Core Insight

What unlocks the optimal approach

  • Start with all numbers positive: <code>[1, 2, ..., n]</code>. Let <code>S = n * (n + 1) / 2</code>.
  • If <code>target < -S</code> or <code>target > S</code> or <code>(S - target) % 2 == 1</code> then no solution - return <code>[]</code>.
  • Let <code>D = S - target</code> (nonnegative). Flipping <code>x</code> to <code>-x</code> reduces the sum by <code>2*x</code>.
  • For <code>x = n</code> down to <code>1</code>: if <code>2x <= D</code> then flip <code>x</code> and set <code>D -= 2x</code>.
  • Build the array using the chosen signs and sort it in ascending order to obtain the lexicographically smallest result.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3752: Lexicographically Smallest Negated Permutation that Sums to Target
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3752: Lexicographically Smallest Negated Permutation that Sums to Target
// package main
// 
// // https://space.bilibili.com/206214
// func lexSmallestNegatedPerm(n int, target int64) []int {
// 	t := int(target)
// 	mx := n * (n + 1) / 2
// 	if t > mx || -t > mx || (mx-t)%2 != 0 {
// 		return nil
// 	}
// 	negS := (mx - t) / 2 // 取负号的元素(的绝对值)之和
// 
// 	ans := make([]int, n)
// 	l, r := 0, n-1
// 	// 从 1,2,...,n 中选一些数,元素和等于 neg
// 	// 为了让取反后字典序尽量小,从大往小选
// 	for x := n; x > 0; x-- {
// 		if negS >= x {
// 			negS -= x
// 			ans[l] = -x
// 			l++
// 		} else {
// 			// 大的正数填在末尾
// 			ans[r] = x
// 			r--
// 		}
// 	}
// 
// 	return ans
// }
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n)
Space
O(1)

Approach Breakdown

BRUTE FORCE
O(n²) time
O(1) space

Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.

TWO POINTERS
O(n) time
O(1) space

Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.

Shortcut: Two converging pointers on sorted data → O(n) time, O(1) space.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Off-by-one on range boundaries

Wrong move: Loop endpoints miss first/last candidate.

Usually fails on: Fails on minimal arrays and exact-boundary answers.

Fix: Re-derive loops from inclusive/exclusive ranges before coding.

Overflow in intermediate arithmetic

Wrong move: Temporary multiplications exceed integer bounds.

Usually fails on: Large inputs wrap around unexpectedly.

Fix: Use wider types, modular arithmetic, or rearranged operations.

Moving both pointers on every comparison

Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.

Usually fails on: A valid pair can be skipped when only one side should move.

Fix: Move exactly one pointer per decision branch based on invariant.

Using greedy without proof

Wrong move: Locally optimal choices may fail globally.

Usually fails on: Counterexamples appear on crafted input orderings.

Fix: Verify with exchange argument or monotonic objective before committing.