Pair Sum
Pair Sum
Send Feedback
Pair Sum
Given array/list can contain duplicate elements.
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 'X'.
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.
1 <= t <= 10^2
0 <= N <= 10^3
0 <= X <= 10^9
Time Limit: 1 sec
1
9
1 3 6 2 5 4 3 2 4
7
7
2
9
1 3 6 2 5 4 3 2 4
12
6
2 8 10 5 -2 5
10
0
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).
#include <iostream>#include <bits/stdc++.h>
using namespace std;
int pairSum(int *arr, int n, int sum) { unordered_map<int, int> m;
long long int ans = 0;
for (int i = 0; i < n; i++) { int b = sum - arr[i];
if (m[b]) { ans += m[b]; }
m[arr[i]]++; } return ans;}
int main(){ int t; cin >> t;
while (t--) { int size; int x;
cin >> size; int *input = new int[size];
for (int i = 0; i < size; i++) { cin >> input[i]; }
cin >> x;
cout << pairSum(input, size, x) << endl;
delete[] input; } return 0;}
Comments
Post a Comment