-
Notifications
You must be signed in to change notification settings - Fork 1
/
Pair sum to 0.cpp
53 lines (40 loc) · 1.28 KB
/
Pair sum to 0.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
Pair Sum to 0
Given a random integer array A of size N. Find and print the count of pair of elements in the array which sum up to 0.
Note: Array A can contain duplicate elements as well.
Input format:
The first line of input contains an integer, that denotes the value of the size of the array. Let us denote it with the symbol N.
The following line contains N space separated integers, that denote the value of the elements of the array.
Output format :
The first and only line of output contains the count of pair of elements in the array which sum up to 0.
Constraints :
0 <= N <= 10^4
Time Limit: 1 sec
Sample Input 1:
5
2 1 -2 2 3
Sample Output 1:
2
*/
#include<unordered_map>
int pairSum(int *arr, int n) {
// Write your code here
unordered_map<int, int> map;
for(int i = 0; i < n; i++) {
map[arr[i]]++;
}
int count = 0;
for(int i = 0; i < n; i++) {
if(arr[i] == 0 and map[arr[i]] > 1) {
count += ((map[arr[i]]) *(map[arr[i]] - 1)) / 2;// n choose 2
map[arr[i]] = 0;
} else if(map[-arr[i]] and arr[i] != 0) {
count += map[arr[i]] * map[-arr[i]];
map[arr[i]] = 0;
map[-arr[i]] = 0;
}
}
return count;
}
// Time Complexity : O(n)
// Auxilary Space : O(n)