Find two elements, so the sum is equal to the given value

Given two sets of "n" numbers A and B. Choose one element from A and one from B so that the sum is equal to the given value of "val".

I have a solution like:

We can hash elements Set A and Set B and check for each element in the set A whether val-arr [i] exists in the Set B hash or not. It takes O (n) and O (n) time. Could there be better solutions with space like O (1) and O (n) time?

+1
source share
1 answer

Since you have both arrays that are NOT sorted, you do NOT have ANY other options, but look at each element one by one. Thus, you cannot reach O(n) . I think the approach you are using is fine.

Read these related posts:

Given the two arrays a and b. Find all pairs of elements (a1, b1) for which a1 belongs to array A and b1 belongs to array B, the sum a1 + b1 = k

Find two elements in the array whose sum is k

+1
source

Source: https://habr.com/ru/post/1438336/


All Articles