Is The Time Complexity Of This Code O(n^2)?
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
Solution 1:
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:
def twoSum(nums, target):
values = dict()
for index, n in enumerate(nums):
if target - n in values:
return values[target - n], index
else:
values[n] = index
print(twoSum([4, 5, 2, 1, 3], 4)) # (3, 4)
- 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 to O(n)
but if you are working with large numbers (negative or positive) you will see an increase in collisions which will result n * log(n)
to n^2
time (especially if the test set given to you tries to target hash collisions).
Post a Comment for "Is The Time Complexity Of This Code O(n^2)?"