<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">Today I will introduce the classic 2 sum problem.</span>
Problem
Given a array of distinct numbers, write the a program to find if there exists a pair of number whose sum is X.
Variation
Given a array of distinct numbers, write the a program to find all pairs of number whose sum is X.
I will just give a simple description of the algorithm using matlab.
Version 1
N=10;
array = rand(1,N);
desired_sum=rand(1)+rand(1);
for i=1:N
for j = 1:N
if array(i)+array(j) == desired_sum
fprintf('%d %d',array(i),array(j));
end
end
end
The complexity of the algorithm is O(n^2).
Version 2
N=10;
array = rand(1,N);
desired_sum=rand(1)+rand(1);
array=sort(array);
for i=1:N
% binary_search here return 0 if it cannot find the element
% or return the index of the element.
[k]=binary_search(array,desired_sum-array(i));
if k ~= 0
fprintf('%d %d',array(i),array(k));
end
end
The complexity of the algorithm is O(nlog(n)).
Version 3
N=5;
array = [1 2 7 3 6];
array=sort(array);
i = 1;
j = N;
x = 9;
while(i < j)
if (array(i) + array(j) == x)
fprintf('%d %d\n',array(i),array(j));
i = i + 1;
j= j - 1;
end
if array(i) + array(j) > x
j=j-1;
end
if array(i) + array(j) < x
i=i+1;
end
end
This algorithm should take about half time of version 2. Let's demonstrate this algorithm really works. For every i, match j to check if they sum to x. if j is to big, j--. If the sum is less than x, we can assert that the we can stop the search for i. Let's search for i+1!!!!
Version 4
The last and the most efficient version is utilizing hashtable, which is a O(n) algorithm. However, it takes much more memory!!!!