This can be done in O (1) space and O (N 2 ) time.
First, let's solve a simpler problem:
For two arrays A and B select one element from each so that their sum is equal to the given number K
Sort both arrays that accept O (NlogN).
Move the pointers i and j so that i points to the beginning of array A and j points to the end of B
Find the sum A[i] + B[j] and compare it with K
- if
A[i] + B[j] == K we found a pair of A[i] and B[j] - if
A[i] + B[j] < K , we need to increase the amount, therefore the increment i . - if
A[i] + B[j] > K , we need to reduce the amount, so decrement j .
This process of finding a pair after sorting takes O (N).
Now let's take the original task. Now we have the third array of C
So now the algorithm:
foreach element x in C find a pair A[i], B[j] from A and B such that A[i] + B[j] = K - x end for
The outer loop starts N times, and for each run we perform the operation O (N), which makes the whole algorithm O (N 2 ).
codaddict Oct 21 2018-10-10 12:28
source share