For the two sum problems, find two numbers in a list that adds up to the target.
My solution is to create a dictionary/hash_table, and then store everything in it as (value, index)
[Note: For duplicate numbers in the list: higher index would override lower index]
Then traverse through the list again to find the other item.
def twoSum(nums, target):
lookup = dict((v, i) for i, v in enumerate(nums))
for i, v in enumerate(nums):
if target - v in lookup and i != lookup[target-v]:
return [lookup[target - v], i]
I think the above algorithm would take O(n * n/2) =, hence O(n^2) time but I see some others say that it only takes linear time. Can someone confirm on this?
n/2
? Also, why do you think it multiplies? It should add.