![]() |
VOOZH | about |
Given an integer N, the task is to find N distinct integers whose sum is N. If there is more than one combination of the integers, print any one of them.
Examples:
Input: N = 3
Output: 1, -1, 3
Explanation:
On adding the numbers that is 1 + (-1) + 3 the sum is 3.Input: N = 4
Output: 1, -1, 0, 4
Explanation:
On adding the numbers that is 1 + (-1) + 0 + (4) the sum is 4.
Approach: The idea is to print N/2 Symmetric Pairs like (+x, -x) so that the resultant sum will always be 0.
Now if integer N is odd, then print N along with these set of integers to make sum of all integers equals to N
If N is even, print 0 and N along with these set of integers to make sum of all integers equals to N.
Below is the implementation of the above approach:
Output:
-1,1,-2,2,5
Time Complexity: O(N/2) which is asymptotically same as O(N).
Space Complexity: O(1) as no extra space has been used.