DEV Community

Bernice Waweru
Bernice Waweru

Posted on • Updated on


Two Sum


Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.


Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Enter fullscreen mode Exit fullscreen mode


We can use a hashmap to store the elements and check if the difference exists and return the indices of the elements.


We initialize an empty dictionary, iterate through the nums array, check the difference between target and a given element.

def twoSum(self, nums: List[int], target: int) -> List[int]:
        for (count,num) in enumerate(nums):
            difference = target-num
            if difference in hashmap:
                return [hashmap[difference],count]
Enter fullscreen mode Exit fullscreen mode

The enumerate() method adds a counter to an iterable and returns it in a form of enumerating object.
enumerate(iterable, start=0)
The counter starts at 0 by default although you can specify the preferred index value from which the counter should start.

The solution to similar problem 3Sum can be found here.

Top comments (0)

An Animated Guide to Node.js Event Loop

>> Check out this classic DEV post <<