Sorry to be a pain. I know it's a classic and I have checked, but I still can't understand why the time cost is O(n).
Here's my code.
def two_sum(L, sum):
targets = {}
for i in range(len(L)):
if L[i] in targets:
return (targets[L[i]], i)
else: targets[sum - L[i]] = i
While I get that L is only iterated over once and that the value look up for a given key is O(1), isn't the search for an actual key in a dict O(n)? Doesn't that mean that for each value in L there is an O(n) look up cost to find if that value is key in the dict, making it a total of O(n^2)?
Apologies if I'm being stupid but when I searched for an answer everyone just seems to be saying the lookup cost in a hash table is O(1), so it's only O(n) * O(1) = O(n).
Edit: Just to clarify, the dict size in this problem grows with n.