Leetcode Two Sum problem solution in Python programming

In the Leetcode Two Sum problem solution in Python programming Given an array of integer nums and an integer target, return indices of the two numbers such that they add up to the 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.

Leetcode Two Sum problem solution in Python programming

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        d = {}
        answer = []
        for x in range(len(nums)):
            if d:
                check = target - nums[x]
                if(check in d):
                    answer.append(d.get(check))
                    answer.append(x)
                    return answer 
                else:
                    d[nums[x]] = x
            else:
                d[nums[x]] = x
        return answer

Also read,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

Your email address will not be published. Required fields are marked *