Two Number Sum (C++) - Interview Question
Find the two numbers in a given array or vector whose sum is equal to the given target value.Return the index of two numbers, lower index value will be the Index 1 and higher will be Index2
#include<iostream>
#include<vector>
#include<unordered_map>
using namespace std;
vector<int> twoSum(const vector<int> &A, int B)
{
unordered_map<int, int> hm;
vector<int> result;
int i;
for(i=0; i<A.size(); i++)
{
int diff = (B - A[i]);
if(hm.find(diff) != hm.end())
{
if(i < hm[diff])
{
result.push_back(i+1);
result.push_back(hm[diff] + 1);
}
else
{
result.push_back(hm[diff] + 1);
result.push_back(i+1);
}
return result;
}
else
{
hm.insert({A[i],i});
}
}
return result;
}
int main()
{
int n;
cout << "Enter the size of the array\n";
cin >> n;
vector<int> v(n);
cout << "Enter the " << n << " elements of the array\n";
for(int i=0; i<n; i++)
{
cin >> v[i];
}
cout << "Enter the target number\n";
int target;
cin >> target;
vector<int> res = twoSum(v, target);
if(res.size() > 0)
{
cout << "Index 1 : " << res[0] << " & Index 2 : " << res[1] << endl;
}
else
{
cout << "No match found\n";
}
return 0;
}
Output :
Enter the size of the array
5
Enter the 5 elements of the array
1 2 4 7 9
Enter the target number
9
Index 1 : 2 & Index 2 : 4
Note : Index are shown as first index is marked as 1 instead of 0.
Comments
Post a Comment