two sum 2 pointer javascript algorithm code example

Example 1: two pointer approach java

The algorithm basically uses the fact that the input array is 
sorted. We start the sum of extreme values (smallest and 
largest) and conditionally move both pointers. We move left 
pointer i when the sum of A[i] and A[j] is less than X. We 
do not miss any pair because the sum is already smaller than X. 
Same logic applies for right pointer j.

Example 2: two sum javascript

var twoSum = function(nums, target) {
    //hash table
    var hash = {};

    for(let i=0; i<=nums.length; i++){
      //current number
        var currentNumber = nums[i];
        //difference in the target and current number
        var requiredNumber = target - currentNumber;
        // find the difference number from hashTable
        const index2 = hash[requiredNumber];

        // if number found, return index 
        // it will return undefined if not found
        if(index2 != undefined) {
            return [index2, i]
        } else {
           // if not number found, we add the number into the hashTable
            hash[currentNumber] = i;

        }
    }
};

Tags:

Java Example