Coding-Ninjas-Competitive-Programming icon indicating copy to clipboard operation
Coding-Ninjas-Competitive-Programming copied to clipboard

Intuitive solution for Pair sum to zero in language tools and time complexity module

Open Nikhil-Patro opened this issue 4 years ago • 1 comments

/* Given a random integer array A of size N. Find and print the pair of elements in the array which sum to 0. Array A can contain duplicate elements. While printing a pair, print the smaller element first. That is, if a valid pair is (6, -6) print "-6 6". There is no constraint that out of 5 pairs which have to be printed in 1st line. You can print pairs in any order, just be careful about the order of elements in a pair. Input format : Line 1 : Integer N (Array size) Line 2 : Array elements (separated by space) Output format : Line 1 : Pair 1 elements (separated by space) Line 2 : Pair 2 elements (separated by space) Line 3 : and so on Constraints : 0 <= N <= 10^4 Sample Input: 5 2 1 -2 2 3 Sample Output : -2 2 -2 2 */

#include<bits/stdc++.h> using namespace std; int pairSum(int arr, int n) { int count=0; unordered_map<int,int> m; for(int i=0;i<n;i++){ m[arr[i]]+=1; } for(int i=0;i<n;i++){ if(arr[i]==0) continue; // we will handle 0 seperately int pos = m[arr[i]]; int neg = m[-arr[i]]; if(pos >0 && neg >0){ count = count + (posneg); m[arr[i]]=0; m[-arr[i]]=0; } } //handle 0 elements int zeroes = m[0]; count = count + (zeroes*(zeroes-1))/2; return count; }

Nikhil-Patro avatar Apr 09 '21 10:04 Nikhil-Patro

If you follow Contribution guidelines It will be easier for me to have a look at your code. I appreciate your effort though.

parikshit223933 avatar Apr 26 '21 18:04 parikshit223933