Skip to content

Latest commit

 

History

History

1-TwoSum

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

Two Sum

Problem can be found in here!

Solution: Hash Table

def twoSum(nums: List[int], target: int) -> List[int]:
    memo = {}
    for index, num in enumerate(nums):
        try:
            return [memo[num], index]
        except KeyError:
            memo[target-num] = index

Explanation: We can solve this problem by iterating the array once. In each iteration, we can memorize the number needed for this number to add up to our target number by using hash map. When we find there is a match in our hash map, we can return the answer.

Time Complexity: O(n), Space Complexity: O(n)