-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPair with given sum in a sorted array.cpp
56 lines (45 loc) · 1.17 KB
/
Pair with given sum in a sorted array.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
54
55
56
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution {
public:
int countPairs(vector<int> &arr, int target) {
// Complete the function
unordered_map<int, int> freq; // To store frequency of elements
int count = 0;
for (int num : arr) {
int complement = target - num;
// Check if complement exists in the frequency map
if (freq[complement] > 0) {
count += freq[complement]; // Count valid pairs
}
freq[num]++; // Update frequency of the current number
}
return count;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
cin.ignore();
while (t--) {
vector<int> arr;
int target;
string input;
getline(cin, input);
stringstream ss(input);
int number;
while (ss >> number) {
arr.push_back(number);
}
cin >> target;
cin.ignore();
Solution obj;
cout << obj.countPairs(arr, target) << endl;
cout << "~\n";
}
return 0;
}
// } Driver Code Ends