two sum leetcode solution

 

two sum algorithm

 

We hope you can improve your skills by exploring this two sum leetcode solution. This post is about solving the 2-sum problem. The complete solution is described in JavaScript.

In this problem, we need to find two different index pairs in an ordered matrix that adds values ​​to a particular goal. You can assume that the matrix has only one pair of integers that sums the desired sums. Note that the matrices are in a non-decreasing order

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

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: 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]

Two Solution

From the example above, we should return the two indexes of the values that sum equal to the target.

A good solution to this problem should take consideration of time complexity, we will map the numbers to their index and look back up of O(n) Time Complexity.

for this solution, we will use the frequency counter approach.

Step 1: Create an instance of Map()

 twoSum  = (nums , target)=> {
var  myMap = new Map();


}

Next, we will run a for loop with the given numbers.

 twoSum  = (nums , target)=> {
  
var  myMap = new Map();

for (let i = 0; i < nums.length; i++) {
  
}
}

Next, we will compare, we will create a result and deduct each element from the target since [A + B = C] then [C – A = B] and store that the result in our newly created Map. We will later check the next result if we have it on our Map. We return the Map.

 const element = nums[i];
    let result  = target  - element;
    if(myMap.has(result)){
      return  [myMap.get(result), i];
    }else{
        myMap.set(element, i);
    }

The complete code is below.

 twoSum  = (nums , target)=> {
  
var  myMap = new Map();

for (let i = 0; i < nums.length; i++) {
    const element = nums[i];
    let result  = target  - element;
    if(myMap.has(result)){
      return  [myMap.get(result), i];
    }else{
        myMap.set(element, i);
    }
}
}

console.log(twoSum(nums, target));
    
    

This Solution takes a time complexity of O(n). You can drop your solution using the comment below.

You can also look in my binary search solution.

You can also solve this same problem yourself on leetcode.

 

 

swagasoft

Fully stack(MEAN) software engineer with over five years of experience participating in the complete product development lifecycle of successfully launched applications. Eager and willing to deliver mission- critical technology solutions.

View all posts by swagasoft →

Leave a Reply

Your email address will not be published. Required fields are marked *