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
?
Use a hash table. Insert every number into your hash table, along with its index. Then, let S
be your desired sum. For every number array[i]
in your initial array, see if S - array[i]
exists in your hash table with an index different than i
.
Average case is O(n)
, worst case is O(n^2)
, so use the binary search solution if you're afraid of the worst case.