Type Here to Get Search Results !

Two sum leetcode problem free solution.

0

 Two sum leetcode problem free solution.


In top interview question The solution of two sum programme using java, python and Go.

Problem Statement :-

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target


Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]
 

Constraints:

2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.


two sum Solution Using Java :-

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        HashMap<Integer,Integer> indexMap = new HashMap<Integer,Integer>();
        for(int i = 0; i < numbers.length; i++){
            Integer requiredNum = (Integer)(target - numbers[i]);
            if(indexMap.containsKey(requiredNum)){
                int toReturn[] = {indexMap.get(requiredNum), i};
                return toReturn;
            }

            indexMap.put(numbers[i], i);
        }
        return null;
    }
}


Two sum solution using Python :-

class Solution:
   def twoSum(self, nums: List[int], target: int) -> List[int]:
       seen = {}
       for i, value in enumerate(nums):
           remaining = target - nums[i]
           
           if remaining in seen:
               return [i, seen[remaining]]
            
           seen[value] = i 


Two sum solution using Go :-

func twoSum(nums []int, target int) []int {
indexMap := make(map[int]int)
for currIndex, currNum := range nums {
if requiredIdx, isPresent := indexMap[target-currNum]; isPresent {
return []int{requiredIdx, currIndex}
}
indexMap[currNum] = currIndex
}
return []int{}
}



Post a Comment

0 Comments