10 Two Sum
Question
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 1:
Input:
N = 6, X = 16
Arr[] = {1, 4, 45, 6, 10, 8}
Output: Yes
Explanation: Arr[3] + Arr[4] = 6 + 10 = 16Example 2:
Input:
N = 5, X = 10
Arr[] = {1, 2, 4, 3, 6}
Output: Yes
Explanation: Arr[2] + Arr[4] = 4 + 6 = 10Your Task: You don't need to read input or print anything. Your task is to complete the function hasArrayTwoCandidates() which takes the array of integers arr, n and x as parameters and returns boolean denoting the answer.
Expected Time Complexity: O(N) Expected Auxiliary Space: O(N)
Constraints: 1 ≤ N ≤ 105 1 ≤ Arr[i] ≤ 105
Naive Approach
Code
bool hasArrayTwoCandidates(int arr[], int n, int x) {
for(int i = 0; i < n; i++)
for(int j = i + 1; j < n; j++)
if(arr[i] + arr[j] == x)
return true;
return false;
}Using `map`
Logic
For each element(say
a) there must be absuch thata + b = xTraverse the given array as
aSince
a + b = xb = x - aCheck the map to see if
bhas already been foundIf found, return
trueAs we have proven that the
aandbnecessary to makea + b = xare present in the array
if not, add
ato the mapThis will be used as
bto make pair with some otherafor next iterations.
Last updated