Similar Problems

Similar Problems not available

Find N Unique Integers Sum Up To Zero - Leetcode Solution

Companies:

LeetCode:  Find N Unique Integers Sum Up To Zero Leetcode Solution

Difficulty: Easy

Topics: math array  

Problem statement:

Given an integer n, return any array containing n unique integers such that they add up to 0.

Example 1: Input: n = 5 Output: [-7,-1,1,3,4] Explanation: These arrays also are accepted [-5,-1,1,2,3], [-3,-1,2,-2,4].

Example 2: Input: n = 3 Output: [-1,0,1]

Example 3: Input: n = 1 Output: [0]

Approach: The sum of any n unique integers that add up to 0 will be 0. This means that if we can create a set of unique integers where the sum adds up to 0, we can easily get the required array. We can generate this set by adding integers from -n/2 to n/2.

If n is even, then each positive integer from 1 to n/2 is matched with corresponding negative integer from -1 to -n/2.

If n is odd, then we add 0 to the set, and then each positive integer from 1 to (n-1)/2 is matched with corresponding negative integer from -1 to -(n-1)/2.

We can use this approach to generate the required array.

Pseudo code:

  1. If n is even, create a list of integers from -n/2 to n/2
  2. If n is odd, create a list of integers from -(n-1)/2 to (n-1)/2 and add 0 to the list
  3. Return the list

Python code:

class Solution(object): def sumZero(self, n): """ :type n: int :rtype: List[int] """ if n % 2 == 0: return list(range(-n//2, 0)) + list(range(1, n//2+1)) else: return list(range(-(n-1)//2, (n-1)//2+1))

Find N Unique Integers Sum Up To Zero Solution Code

1