DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on

Leetcode - 1. Two Sum

Using Hashmap (Optimal solution)

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function (nums, target) {
    let myMap = new Map();

    for (let i = 0; i < nums.length; i++) {
        myMap.set(nums[i], i);
    }
    for (let i = 0; i < nums.length; i++) {
        let remaining = target - nums[i];
        if (myMap.has(remaining) && myMap.get(remaining) !== i) {
            return [i, myMap.get(remaining)];
        }
    }
};
Enter fullscreen mode Exit fullscreen mode

Using Pointers

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {

   let left = 0;
   let right = 1


   while(left <= nums.length-1){

       if(nums[left] + nums[right] === target){
           return [left,right]
       }else if (right === nums.length-1){
           left++;
           right = left+1;
       }
       else{
           right++;
       }
   }
};
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

If you found this post useful, please drop a ❤️ or leave a kind comment!

Okay