- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

# 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

- if target − A[i] is present in res

Let us see the implementation to get better understanding

## Example

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]

- Related Articles
- Sum of Two Integers in Python
- Two Sum Less Than K in Python
- Check if sum of divisors of two numbers are same in Python
- Program to find maximum sum of two non-overlapping sublists in Python
- Program to find the sum of the lengths of two nonoverlapping sublists whose sum is given in Python
- Two Sum BSTs in C++
- Two sum in BSTs in JavaScript
- Path Sum in Python
- Combination Sum in Python
- sum() function in Python
- Program to find minimum operations needed to make two arrays sum equal in Python
- Find sub-arrays from given two arrays such that they have equal sum in Python
- Program to find sum of two numbers which are less than the target in Python
- Minimum Path Sum in Python
- Reverse sum of two arrays in JavaScript

Advertisements