Given an integer N, our task is to print N distinct numbers such that their sum is 0.
Input: N = 3
Output: 1, -1, 0
On adding the numbers that is 1 + (-1) + 0 the sum is 0.
Input: N = 4
Output: 1, -1, 2, -2
On adding the numbers that is 1 + (-1) + 2 + (-2) the sum is 0.
Approach: To solve the problem mentioned above the main idea is to print Symmetric Pairs like (+x, -x) so that the sum will always be 0. The edge case to the problem is to observe that if integer N is odd, then print one 0 along with the numbers so that sum is not affected.
Below is the implementation of the above approach:
1, -1, 2, -2, 3, -3, 4, -4, 5, -5,
Time Complexity: O(log N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.