Q16:Given an array Arr of N positive integers and another number X. Determine whether or not there exist two elements in Arr whose sum is exactly X.
Example :
Input:
N = 6, X = 16
Arr[] = {1, 4, 45, 6, 10, 8}
Output: Yes
Explanation: Arr[3] + Arr[4] = 6 + 10 = 16
Solution:
class Solution{
public:
// Function to check if array has 2 elements
// whose sum is equal to the given value
bool hasArrayTwoCandidates(int arr[], int n, int x) {
// code here
sort(arr,arr+n);
int l=0;
int r=n-1;
while(l<r){
if(arr[l]+arr[r]==x){
return true;
}
else if(arr[l]+arr[r]>x){
r--;
}
else
l++;
}
return false;
}
};
Explantion:
>We have to just return the yes and no so order does not matter so first we sort
the array than traverse the array and try to findout the possbile pair if it is
available then we return true otherwise we return false;
If anyone have better solution so please comment:)