I am trying to make algorithm that takes two arrays, S and T of n integers and integer k. The algorithm checks whether the arrays have integers s and t so s+t=k.( s in S and t in T.) The algorithm is supposed to have run time of O(n log n).
Have tried to think of something that sort array T and use for loop to go through S and use binary search to see if I find integer like k – S[i] for every element in S. But that will always have running time greater than n log n, i think.
Not looking for someone to write the code. Only asking here to get some ideas.
Sort the two lists, this is O(n log n).
Then set up two iterators. One iterator starts at the lowest value in S and goes forward through ever-increasing values in S. The other iterator starts at the highest value in T and iterates through ever-decreasing values.
Repeat the following:
This second phase should cause, at most, 2N advances, and hence is O(n). So the total complexity is O(n log n).
This has the same complexity as repeated binary search, but this algorithm should be faster, especially for large n.