-
Notifications
You must be signed in to change notification settings - Fork 0
/
Two_Sum_Pair_With_Given_Sum.cpp
55 lines (47 loc) · 1.35 KB
/
Two_Sum_Pair_With_Given_Sum.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
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function template for C++
class Solution {
public:
// Function to check if array has 2 elements
// whose sum is equal to the given value
bool hasArrayTwoCandidates(vector<int>& arr, int x) {
map<int, int> mpp;
for(int i = 0; i < arr.size(); i++) mpp[arr[i]]++;
for(int i = 0; i < arr.size(); i++)
{
int find = x - arr[i];
if(mpp.find(find) != mpp.end())
{
if(find != arr[i] || mpp[find] > 1) return true;
}
}
return false;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
cin.ignore(); // To discard any leftover newline characters
while (t--) {
int x;
cin >> x;
cin.ignore(); // To discard any leftover newline characters
vector<int> arr;
string input;
getline(cin, input); // Read the entire line for the array elements
stringstream ss(input);
int number;
while (ss >> number) {
arr.push_back(number);
}
Solution ob;
auto ans = ob.hasArrayTwoCandidates(arr, x);
cout << (ans ? "true" : "false") << endl;
}
return 0;
}
// } Driver Code Ends