- Related Questions & Answers
- Sum of Two Integers in Python
- Two Sum Less Than K in Python
- Two Sum BSTs in C++
- Two sum in BSTs in JavaScript
- Program to find maximum sum of two non-overlapping sublists in Python
- Check if sum of divisors of two numbers are same in Python
- Sum of two large numbers in C++
- Reverse sum of two arrays in JavaScript
- Multiply and Sum Two Arrays in JavaScript
- MongoDB order by two fields sum?
- Program to find the sum of the lengths of two nonoverlapping sublists whose sum is given in Python
- Maximum Sum Path in Two Arrays in C++
- Two sum problem in linear time in JavaScript
- Path Sum in Python
- Combination Sum in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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_list = [2,8,12,15] target = 20

[1, 2]

Advertisements