Reputation: 5451
Two sets of 'n' numbers are given A and B. Chose one element from A and one from B such that the sum is equal to a given value, 'val'.
I have got the solution as:
We can hash the elements of Set A and Set B and check for every element in set A whether val-arr[i] exists in the hash of Set B or not. This would take O(n) time and O(n) space Can there be a better solutions with space as O(1) and time O(n)?
Upvotes: 1
Views: 3152
Reputation: 6169
As you have both the arrays NOT sorted, you have NO other option but look at every element one-by-one. So, you cannot get below O(n)
running time. I think the approach you are using is ok.
Read these related posts:
Find two elements in an array that sum to k
Upvotes: 1