m = O(n) means that m bounded by a constant multiple of n , not necessarily less than it.
What you can do is. Get an array of size k+1 (so the memory is O(m) , which is also O(n) ). Call this array C Initialize all values ββas untagged, say -1. This is O(m) , which is also O(n) .
Now you know that k <= 2m , because A[i] and B[i] are <= m . So, you go through array A , mark all kA[i] in C , so C[kA[i]] = i (That is, if kA[i] >= 0 , if the indices begin with 0 ). This is O(n) . Then go through array B and for each B[j] check if C[B[j]] checked. If so, then C[B[j]] marks some index in A , where B[j]+A[C[B[j]]] = k . Going B and checking the label is also O(n) . If you do not find a match, there is no such pair.
The general algorithm is O(n) .
Here is an example:
n = 5 m = 15 A = [1 7 4 2 10] B = [8 14 3 13 11] k = 20
Going through A , you get:
C: [-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 4 -1 -1 1 -1 -1 2 -1 3 0 -1]
(Interval for better visualization). Then you check B :
B[0] -> C[8] -> -1 mismatch B[1] -> C[14] -> -1 mismatch B[2] -> C[3] -> -1 mismatch B[3] -> C[13] -> 1 match -> B[3] + A[1] = 20
B[3] was 13, and A[1] was 7.
source share