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

Example

 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]
         else:
            required[nums[i]]=i
input_list = [2,8,12,15]
ob1 = Solution()
print(ob1.twoSum(input_list, 20))

Input

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

Output

[1, 2]

Updated on: 28-Apr-2020

16K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements