Sorting two lists, this is O (n log n).
Then configure two iterators. One iterator starts with the smallest value in S and advances along constantly increasing values ββin S. Another iterator starts with the highest value in T and iterates over constantly decreasing values.
Repeat the following:
- if the current values ββadd up to a number greater than k, advance the T-iterator. This should reduce the amount.
- if the current values ββadd up to a number less than k, advance the S-iterator. This should increase the amount.
- if the current values ββare summed with k, then they exit successfully.
This second phase should cause, at most, 2N, and therefore O (n). So the overall complexity is O (n log n).
This has the same complexity as repeated binary searches, but this algorithm should be faster, especially for large n.
source share