The problem finds two items in the array that add up to target value. It returns an array w/ the index of the correct values.
I think the time complexity is n^2 because the while loop runs through array once so n time. And in the worst case, it has to repeat this n times. So n*n running time.
Even though the number of elements it has to iterate through decreases each time, we drop the constants when calc. time complexity.
Is this analysis correct? Any recommendations for bringing it down to n?
def twoSum(nums, target):
indx = []
size = len(nums)
if (size < 2):
return indx
x = 0
y = size - 1
while(x < y):
if( (nums[x] + nums[y]) == target):
indx[0] = x
indx[1] = y
break
elif ( (y - 1) == x):
x = x + 1
y = size - 1
else:
y = y -1
return indx
You can do
O(n)
, this is a google interview question that they have a video on YouTube for I believe. Or at least they had a very similar problem:- Edit -
Per the comments below, this solution technically still has a worst case of
O(n^2)
do to hash collisions. For most cases you should get close toO(n)
but if you are working with large numbers (negative or positive) you will see an increase in collisions which will resultn * log(n)
ton^2
time (especially if the test set given to you tries to target hash collisions).