DEV Community

Bernice Waweru
Bernice Waweru

Posted on • Updated on

Two Sum

Instructions

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.

Example

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

Approach

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

Breakdown

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]:
        hashmap={}
        for (count,num) in enumerate(nums):
            difference = target-num
            if difference in hashmap:
                return [hashmap[difference],count]
            hashmap[num]=count
        return
Enter fullscreen mode Exit fullscreen mode

The enumerate() method adds a counter to an iterable and returns it in a form of enumerating object.
Syntax:
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)