Given an std::vector
of distinct elements sorted in ascending order, I want to develop an algorithm that determines whether there are two elements in the collection whose sum is a certain value, sum
.
I've tried two different approaches with their respective trade-offs:
I can scan the whole vector and, for each element in the vector, apply binary search (
std::lower_bound
) on the vector for searching an element corresponding to the difference betweensum
and the current element. This is an O(n log n) time solution that requires no additional space.I can traverse the whole vector and populate an
std::unordered_set
. Then, I scan the vector and, for each element, I look up in thestd::unordered_set
for the difference betweensum
and the current element. Since searching on a hash table runs in constant time on average, this solution runs in linear time. However, this solution requires additional linear space because of thestd::unordered_set
data structure.
Nevertheless, I'm looking for a solution that runs in linear time and requires no additional linear space. Any ideas? It seems that I'm forced to trade speed for space.