#1304

Find N Unique Integers Sum up to Zero

Easy
ArrayMathArrayMathematical properties
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(n)

Instead of generating combinations, we can directly construct the required array by leveraging the properties of integers. For any n, we can use pairs of integers that cancel each other out.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize an empty array.
  2. 2Step 2: For each integer from 1 to n/2, add both -i and i to the array.
  3. 3Step 3: If n is odd, append 0 to the array.
  4. 4Step 4: Return the constructed array.
solution.py10 lines
1# Full working Python code
2
3def find_n_unique_integers(n):
4    result = []
5    for i in range(1, n // 2 + 1):
6        result.append(i)
7        result.append(-i)
8    if n % 2 == 1:
9        result.append(0)
10    return result

Complexity note: This complexity is O(n) because we are iterating through n/2 integers to construct the result array, which is linear in terms of n.

  • 1Using pairs of integers that cancel each other out is a straightforward way to ensure the sum is zero.
  • 2For odd n, including zero balances the array.

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