I saw a interview question as follows: Give an unsorted array of integers A and and an integer I, find out if any two members of A add up to I.
any clues?
ti
X
in A
, perform a binary search for I-X
. If I-X
is in A
, we have a solution.This is O(nlogn)
.
If A
contains integers in a given (small enough) range, we can use a trick to make it O(n)
:
V
. For each element X
in A
, we increment V[X]
.V[X]
we also check if V[I-X]
is >0
. If it is, we have a solution.For example, loop and add possible number to set or hash and if found, just return it.
>>> A = [11,3,2,9,12,15]
>>> I = 14
>>> S = set()
>>> for x in A:
... if x in S:
... print I-x, x
... S.add(I-x)
...
11 3
2 12
>>>
O(n) time and O(1) space
If the array is sorted there is a solution in O(n) time complexity.
Suppose are array is
array = {0, 1, 3, 5, 8, 10, 14}
And our x1 + x2 = k = 13
, so output should be= 5, 8
array[ptr1] + array[ptr2]
if sum > k then decrement ptr2 else increment ptr1
Same thing explained in detail here. Seems like an Amazon interview Question http://inder-gnu.blogspot.com/2007/10/find-two-nos-in-array-whose-sum-x.html