File: find-n-unique-integers-sum-up-to-zero/solution.py

Date: 2026-06-06

Time: 16:39

find-n-unique-integers-sum-up-to-zero/solution.py

Purpose

This file solves LeetCode 1304: Find N Unique Integers Sum up to Zero. Given an integer n, it returns any array of n unique integers that sum to zero. It follows the repo's convention of one Solution class per problem directory.

Key Components

Solution.sumZero(n: int) -> List[int] — The single method. It constructs the result by pairing positive and negative integers symmetrically around zero:

Patterns

Symmetric cancellation — The core technique. Rather than solving a constraint satisfaction problem, the solution exploits the fact that i + (-i) = 0 for any integer. This is the simplest construction possible and avoids any need for tracking a running sum.

Greedy construction — The result is built in a single pass with no backtracking. The algorithm never needs to revisit prior choices because every pair is independently valid.

Dependencies

Flow

1. Initialize empty result list.

2. Loop i from 1 to n // 2 inclusive — append i and -i on each iteration (2 elements per iteration, so n // 2 iterations produce 2 * (n // 2) elements).

3. If n is odd, one slot remains — fill it with 0.

4. Return result.

For n = 5: loop produces [1, -1, 2, -2], then 0 is appended → [1, -1, 2, -2, 0]. Sum = 0, all unique, length = 5.

Invariants

Error Handling

None. The method trusts that n >= 1 per the problem constraints. If n = 0, it returns [] (the loop doesn't execute, the odd check fails). No validation, no exceptions — appropriate for a LeetCode solution where inputs are guaranteed valid.

Complexity