Placement

leet code : Two sum Problem solution – Java || CPP || JavaScript || Python

Problem Statement

This is another article in the series leetcode problem solutions and this article is a solution to leetcode 1 two sum problem.

Once you have a good understanding of two sum problem, it should help you solve advanced level problems like three sum which in some ways a continuation of the two sum problem.

Consider you are given an array of integers and a target sum, return indices of two numbers in the array such that they add up to the given target. You may assume that each input would have exactly one solution. Also, you cannot use the same element twice. You are allowed to return the answer in any order.

Example

Example 1:

Input: nums = [7,2,13,11], target = 9
Output: [0,1]
Example 2:

Input: nums = [7,3,5], target = 8
Output: [1,2]

Solution:

First, let us attempt to comprehend the issue statement. We are provided an array of integer items as well as a goal total. Our task is to build an algorithm that returns the indices of two entries in this array so that when we combine these two elements, the total should equal the goal amount.

In example 1, the supplied array is [7,2,13,11], and the specified goal total is 9. Looking at the supplied array, the pair that adds to the goal total 9 is (7,2), i.e. 7+2 = 9. As a consequence, our method should return(0,1) as the result because they are the indices of items 7 and 2 in the supplied array, respectively.

Solution 1: Use of Force

A simple approach to this problem is to look for every possible pair in the supplied array.

We must do the following steps for a given input array nums:

Run two loops to test each combination in the supplied array.

To acquire all potential pairs, fix the outer loop at a given index and shift the inner loop. The outer loop extends from i=0 to i=n-2, whereas the inner loop extends from j=i+1 to j=n-1.

Check if the integers represented by the outside and inner loop indexes add up to the goal total in each iteration of the inner loop.

If nums[outerLoopIndex] + nums[innerLoopIndex] equals target, the outcome is outerLoopIndex, innerLoopIndex. Otherwise, keep iterating to ensure

JAVA

Map hm = new HashMap();
    for(int i=0;i {
         hm.put(nums[i],i);
}
for(int i=0;i {
   int k =nums[i];
   if(k == target && hm.containsKey(0) )
  {
         arr[0]= i;
         arr[1]=hm.get(0);
         break;
  }
else if(hm.containsKey(target-k) )
{
   if(hm.get(target-k)>i)
     {      arr[0]= i;
             arr[1]=hm.get(target-k);
              break;} 
  }
}
   return arr;
}

CPP:

vector twoSum(vector& nums, int target) {
   unordered_mapans;
   for(int i=0;iint k=target-nums[i];
      if(ans.count(k)){
           return {ans[k],i};
   }
    ans[nums[i]]=i;
}
  return {-1,-1};
}

Python :

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

JavaScript Solution :

function twoSum(nums, target) {
      let vals = {};

      for (let i = 0; i < nums.length; i++) {
          if (target - nums[i] in vals) {
    
          return [vals[target-nums[i]], i];
            }
           else {
       vals[nums[i]] = i;
         }
      }
     return [];
};
Facebook
Twitter
LinkedIn

6 thoughts on “leet code : Two sum Problem solution – Java || CPP || JavaScript || Python”

  1. bro you solved it by class method and python code for this problem is simpler but i cant understand why we use class and all so please refer me article so that i can understand is use.
    Thankyou.

    Reply
  2. Itís nearly impossible to find well-informed people for this subject, however, you seem like you know what youíre talking about! Thanks

    Reply

Leave a Comment