DEV Community

Cover image for 1. Two Sum - Leetcode - JavaScript Solution using HashMap - by Abu Saleh Faysal
Abu Saleh Faysal
Abu Saleh Faysal

Posted on

1. Two Sum - Leetcode - JavaScript Solution using HashMap - by Abu Saleh Faysal

I previously solved this problem using two for loops. However, that was not a very efficient way to solve this problem. So, this time I solved this problem using HashMap.

Solution:

Step 01: Hashmap is a set of key, value pairs. I declared a variable which is an empty hashmap.

*Step 02: * Using a for loop, iterate the whole array and find out the needed number to meet the target (for each individual number) using this equation: needed number = target - individual number.

Step 03: Check if the hashmap contains the needed number or not, if it contains the needed number, then we simply return the needed number index and the index of that particular array element that gave us the needed number. If it does not meet the condition then, I simply store the number and the index in the hashmap.

Code:

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

    for(let i = 0; i < nums.length; i++) {
        let neededNumber = target - nums[i];

        if(hashMap.has(neededNumber)) {
            return [i, hashMap.get(neededNumber)];
        } 
        hashMap.set(nums[i], i);

    }
};
Enter fullscreen mode Exit fullscreen mode

If you want me to publish more posts like this, Buy me a coffee.

πŸ‘‰ YouTube Channel Link: https://www.youtube.com/channel/UCW_09Nbobf4URLkAlEo84sw
πŸ‘‰ PlayList Link: https://youtube.com/playlist?list=PLUnklBXn8NSefCpBaLe39mds6dQx-tDDD

πŸ‘‰ Connect with me (LinkedIn): https://www.linkedin.com/in/abusalehfaysal
πŸ‘‰ Follow our LinkedIn Page:
πŸ‘‰ Like our Facebook page: https://www.facebook.com/thebacklogprogrammer/
πŸ‘‰ Join our community (Facebook group): https://www.facebook.com/groups/5500588936676942/
πŸ‘‰ Follow me at: https://www.facebook.com/AbuSalehFaysal10
πŸ‘‰ Twitter: https://twitter.com/AbuSalehFaysal

πŸ‘‰ Abu Saleh Faysal’s Blog: https://abusalehfaysal.hashnode.dev/
πŸ‘‰ Hasnode: https://hashnode.com/@AbuSalehFaysal
πŸ‘‰ Dev Community: https://dev.to/abusalehfaysal
πŸ‘‰ freeCodeCamp: https://www.freecodecamp.org/abusalehfaysal
πŸ‘‰ Medium: https://abusalehfaysal.medium.com/

πŸ‘‰ GitHub: https://github.com/AbuSalehFaysal
πŸ‘‰ GitLab: https://gitlab.com/AbuSalehFaysal

Top comments (0)