« Pair sum in array

Problem

You have been given an integer array/list(ARR) and a number 'num'. Find and return the total number of pairs in the array/list which sum to 'num'.

Note:

Given array/list can contain duplicate elements.

Input format :

The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow.

First line of each test case or query contains an integer 'N' representing the size of the first array/list.

Second line contains 'N' single space separated integers representing the elements in the array/list.

Third line contains an integer 'num'.

Output format :

For each test case, print the total number of pairs present in the array/list.

Output for every test case will be printed in a separate line.

Constraints :

1 <= t <= 10^2

0 <= N <= 10^4

0 <= num <= 10^9

Time Limit: 1 sec

Sample Input 1:

1

9

1 3 6 2 5 4 3 2 4

7

Sample Output 1:

7

Sample Input 2:

2

9

1 3 6 2 5 4 3 2 4

12

6

2 8 10 5 -2 5

10

Sample Output 2:

0

2

Explanation for Input 2:

Since there doesn't exist any pair with sum equal to 12 for the first query, we print 0.

For the second query, we have 2 pairs in total that sum up to 10. They are, (2, 8) and (5, 5).

Solution

1#include <iostream>
2#include <iomanip>
3#include <algorithm>
4#include <string>
5#include <cstring>
6#include <vector>
7#include <cmath>
8#include <map>
9#include <climits>
10// climits for INT_MIN
11#include <unordered_map>
12using namespace std;
13
14int pairSum(int *arr, int n, int num)
15{
16 int ans = 0;
17 unordered_map<int, int> umap;
18 for (int i = 0; i < n; i++)
19 {
20 if (umap.find(arr[i]) != umap.end())
21 {
22 umap[arr[i]] = umap[arr[i]] + 1;
23 }
24 else
25 {
26 umap[arr[i]] = 1;
27 }
28 }
29
30 for (auto &it : umap)
31 {
32 if (num - it.first != it.first)
33 {
34 if (umap.find(num - (it.first)) != umap.end())
35 {
36 ans = ans + (umap[num - (it.first)] * it.second);
37 }
38 }
39 else
40 {
41 if (it.second > 1)
42 {
43 ans = ans + (((it.second - 1) * (it.second)) / 2);
44 }
45 }
46 umap[it.first] = 0;
47 }
48 return ans;
49}
50
51int main()
52{
53 int t;
54 cin >> t;
55
56 while (t > 0)
57 {
58 int size;
59 int x;
60
61 cin >> size;
62 int *input = new int[size];
63
64 for (int i = 0; i < size; i++)
65 {
66 cin >> input[i];
67 }
68
69 cin >> x;
70
71 cout << pairSum(input, size, x) << endl;
72
73 delete[] input;
74 t--;
75 }
76 return 0;
77}