Two Sum in Python

Suppose we have an array of integers. We have to return the indices of two integers, such that if we add them up, we will reach to a specific target that is also given. Here we will take one assumption, that is always there will be one unique solution in the array, so no two set of indices for same target will be there.

For an example, suppose the array is like A = [2, 8, 12, 15], and the target sum is 20. Then it will return indices 1 and 2, as A[1] + A[2] = 20.

To solve this, we will loop through each element of the array. So follow these steps to solve this.

  • Define one map to hold the result called res
  • For index i in range 0 to n – 1 (where n is the number of elements in the array)
    • if target − A[i] is present in res
      • return res[target − A[i]] and i as indices
    • Otherwise put i into the res as res[A[i]] − = i

Let us see the implementation to get better understanding


 Live Demo

class Solution(object):
   def twoSum(self, nums, target):
      :type nums: List[int]
      :type target: int
      :rtype: List[int]
      required = {}
      for i in range(len(nums)):
         if target - nums[i] in required:
            return [required[target - nums[i]],i]
input_list = [2,8,12,15]
ob1 = Solution()
print(ob1.twoSum(input_list, 20))


input_list = [2,8,12,15]
target = 20


[1, 2]