How can I write an algorithm to check if the sum of any two numbers in an array/list matches a given number
with a complexity of nlogn
?
This can be done in O(n)
using a hash table. Initialize the table with all numbers in the array, with number as the key, and frequency as the value. Walk through each number in the array, and see if (sum - number)
exists in the table. If it does, you have a match. After you've iterated through all numbers in the array, you should have a list of all pairs that sum up to the desired number.
array = initial array
table = hash(array)
S = sum
for each n in array
if table[S-n] exists
print "found numbers" n, S-n
The case where n and table[S-n] refer to the same number twice can be dealt with an extra check, but the complexity remains O(n)
.