Two sum problem in linear time in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of numbers as the first argument and a target sum as the second argument.

The function should find and return the index of two such numbers from the array (consecutive or non−consecutive) that adds up to give the target sum (if there are any). The condition is that we have to do this in linear time (one iteration).

We will keep count of the iterated numbers using a map, and if at any point we encounter two numbers that give the target sum we return right away.

Example

The code for this will be −

const arr = [1, 3, 5, 7, 9, 11];
const target = 16;
const twoSum = function(arr, target) {
   const map = new Map();
   for(let i = 0; i < arr.length; i++) {
      let num = arr[i];
      if(map.get(num) === undefined){
         map.set(target−num, i)
      }else{
         return [map.get(num), i]
      };
   };
};
console.log(twoSum(arr, target));

Output

And the output in the console will be −

[3, 4]
raja
Published on 21-Nov-2020 10:20:45
Advertisements