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

Abu Saleh Faysal
2 min readNov 13, 2022

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);

}
};

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

👉 YouTube Channel Link: youtube.com/channel/UCW_09Nbobf4URLkAlEo84sw

👉 PlayList Link: youtube.com/playlist?list=PLUnklBXn8NSefCpB..

👉 Connect with me (LinkedIn): linkedin.com/in/abusalehfaysal

👉 Follow our LinkedIn Page: linkedin.com/company/thebacklogprogrammer

👉 Like our Facebook page: facebook.com/thebacklogprogrammer

👉 Join our community (Facebook group): facebook.com/groups/5500588936676942

👉 Follow me at: facebook.com/AbuSalehFaysal10

👉 Twitter: twitter.com/AbuSalehFaysal

👉 Abu Saleh Faysal’s Blog: abusalehfaysal.hashnode.dev

👉 Hasnode: hashnode.com/@AbuSalehFaysal

👉 Dev Community: dev.to/abusalehfaysal

👉 freeCodeCamp: freecodecamp.org/abusalehfaysal

👉 Medium: abusalehfaysal.medium.com

👉 GitHub: github.com/AbuSalehFaysal

👉 GitLab: gitlab.com/AbuSalehFaysal

--

--

Abu Saleh Faysal

Software Engineer at Onethread | Front-End Developer | Blockchain Enthusiast | JavaScript | TypeScript | React | Redux