↓Skip to main content
  1. LeetCode/

LeetCode 1304: Find N Unique Integers Sum up to Zero

·1 min· ·
LeetCode Easy Math Array
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2025-07-21

  • Submissions: Wrong Answer ×2 → Accepted

Approach
#

Place i and -i in pairs (i = 1..n/2): each pair sums to 0 and nothing repeats. When n is odd, add one 0.

My Attempts
#

  1. Attempt 1 used range(-n//2, n//2 + 1), one number too many for even n (it includes 0). For n = 2 it returned [-1, 0, 1], three numbers.
  2. Attempt 2 lowered the upper bound for even n, giving [-1, 0], which does not sum to 0.
  3. Generating -n//2..n//2 and removing the middle 0 for even n passed.

Solution
#

class Solution:
    def sumZero(self, n: int) -> List[int]:
        res = []
        for i in range(1, n // 2 + 1):
            res += [i, -i]                         # each pair cancels
        if n % 2:
            res.append(0)
        return res

Complexity
#

Time O(n), space O(n) for the output.

Mistakes to Avoid
#

  • With even n there is no room for 0 (it would add a number or force removing another).

Interview Explanation
#

I place i and -i in pairs, each summing to 0, for n / 2 pairs, and add a 0 when n is odd. Time O(n).

Related

LeetCode 1030: Matrix Cells in Distance Order
·2 mins
LeetCode Easy Array Math Geometry Sorting
LeetCode 1030 note: list every coordinate and sort by Manhattan distance to the center; return coordinates, not distances
LeetCode 989: Add to Array-Form of Integer
·2 mins
LeetCode Easy Array Math
LeetCode 989 note: treat k as the carry, add from the last element backwards, and keep prepending digits while k remains
LeetCode 908: Smallest Range I
·1 min
LeetCode Easy Array Math
LeetCode 908 note: lower the maximum by k and raise the minimum by k; the answer is max(0, max - min - 2k)
LeetCode 914: X of a Kind in a Deck of Cards
·2 mins
LeetCode Easy Array Hash-Table Math Counting
LeetCode 914 note: every card count must be divisible by one X >= 2, i.e. the GCD of all counts is at least 2
LeetCode 892: Surface Area of 3D Shapes
·2 mins
LeetCode Easy Array Math Geometry Matrix
LeetCode 892 note: a stack of v cubes has 4v + 2 faces; subtract 2 × min for each overlap with the stacks above and to the left
LeetCode 883: Projection Area of 3D Shapes
·1 min
LeetCode Easy Array Math Geometry Matrix
LeetCode 883 note: the top view counts nonzero cells, and the front and side views sum each row’s and each column’s maximum