Solving Two Sum in Python

The challenge

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.


Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

The solution in Python

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        # keep a hashmap of items found
        seen = {}
        # loop through the nums, with int and value
        for i, v in enumerate(nums):
            # set remaining to the target minus the value
            remaining = target - v
            # check if the new value is in the hashmap
            if remaining in seen:
                # return it and the index
                return [seen[remaining], i]
            # otherwise, put it on the map instead
            seen[v] = i
        # nothing found, return an empty list
        return []
Notify of
Inline Feedbacks
View all comments