You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
/* 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;
}
The text was updated successfully, but these errors were encountered:
/* 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;
}
The text was updated successfully, but these errors were encountered: