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
?
Here is an algorithm that runs in O(n) if array is already sorted or O(n log n) if it isn't already sorted. Takes cues from lot of other answers here. Code is in Java, but here is a pseudo code as well derived from lot of existing answers, but optimized for duplicates generally
Use these variables to compute existence of target in the array; set the currentValue to array[ith]; set newTarget to target - currentValue; set expectedCount to 2 if currentValue equals newTarget or 1 otherwise
AND return true only if a. we never saw this integer before AND b. we have some value for the newTarget in the map we created c. and the count for the newTarget is equal or greater than the expectedCount
OTHERWISE repeat step 4 till we reach end of array and return false OTHERWISE;
Like I mentioned the best possible use for a visited store is when we have duplicates, it would never help if none of elements are duplicates.
Java Code at https://gist.github.com/eded5dbcee737390acb4