Two Sum (coding problem)
First, solve the problem on your own or just dry run it.
here is the leetcode problem
//this takes the O(n log n ) time complexity
// spsce complexity is O(1) which is constant space.
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int twonumberSum(int array[],int targetSum,int n)
{
sort(array, array + n);
int left = 0;
int right =n-1;
while (left < right) {
int currentSum = array[left] + array[right];
if (currentSum == targetSum) {
cout<<array[left]<<’ ‘;
cout<<array[right];
break;
}
else if (currentSum < targetSum) {
left++;
}
else if (currentSum > targetSum) {
right — ;
}
}
return {};
}
int main()
{
int array[]={-4,11,-1,8,1,6,3,5};
int n = sizeof(array) / sizeof(array[0]);
//cout<<”size is “<<n;
int targetSum=17;
twonumberSum(array,targetSum,n);
return 0;
}