Find N Unique Integers Sum up to Zero in C++

C++Server Side ProgrammingProgramming

Suppose we have an integer n. We have to return any array that contains n unique integers, such that they add up to 0. So if input is n = 5, then one possible output will be [-7, -1, 1, 3, 4]

To solve this, we will follow these steps −

  • take an array A as final answer, and take x := 0
  • for i in range 0 to n – 2
    • A[i] = (i + 1)
    • x := x + i + 1
  • A[n – 1] = x
  • return A

Example

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<int> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
   public:
      vector<int> sumZero(int n) {
         vector <int> ans(n);
         int x = 0;
         for(int i = 0; i < n - 1; i++){
            ans[i] = (i + 1);
            x += (i + 1);
         }
         ans[n - 1] = -x;
         return ans;
      }
};
main(){
   Solution ob;
   print_vector(ob.sumZero(10)) ;
}

Input

10

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9, -45, ]
raja
Published on 20-Jan-2020 07:00:34
Advertisements