Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Nikhil-Patro opened this issue Apr 9, 2021 · 1 comment

Comments

@Nikhil-Patro
Copy link

/* 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 + (pos
neg);
m[arr[i]]=0;
m[-arr[i]]=0;
}
}
//handle 0 elements
int zeroes = m[0];
count = count + (zeroes*(zeroes-1))/2;
return count;
}

@parikshit223933
Copy link
Owner

parikshit223933 commented Apr 26, 2021

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants