Back to photostream

Find N Unique Integers Sum up to Zero Leetcode Solution

The problem Find N Unique Integers Sum up to Zero Leetcode Solution, provides us with an integer. It asks us to return n unique integers that sum up to 0. So, the question is pretty simple to understand. So, before diving into the solution. Let us take a look at a few examples.

 

n = 5

 

Explanation: Well, there can be multiple outputs to the problem. But let us take the given output. All the integers in the output are unique. Thus satisfying the imposed condition and the sum of all the given integers is 0. Hence, both the conditions are satisfied.

n = 3

 

Explanation: The output given has all unique integers and their sum is also 0. Thus, the output satisfies all the imposed conditions.

Approach for Find N Unique Integers Sum up to Zero Leetcode Solution

The approach for the problems is most of the times is cracking the pattern. There is always some underlying patterns in these type of questions. So, whenever we try to find the pattern for a question. Always try to find the answer for smaller values of n, then try to find the pattern. For n = 1, output can be 0. For n = 2, output can be . Similarly for n = 3, output can be , for n = 4, output can be . So, we see a pattern that the output forms AP where if the value of n is odd. The middle element is 0. If the value of n is even then the (n+1)/2 element is 1. So, using this information, we can devise a formula. The formula can be a = 2*i+1-n. Now, we simply use this formula to fill the n elements of the array.

Code

 

www.tutorialcup.com/leetcode-solutions/find-n-unique-inte...

21 views
1 fave
0 comments
Uploaded on September 6, 2021