LeetCode TwoSum Explained!

Adarsh gupta
2 min readApr 25, 2023

--

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

Solution

/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
function twoSum(nums, target) {
const memo = {};
for (let i = 0; i < nums.length; i++) {
const needed = target - nums[i];
// console.log(needed)
let index2 = memo[needed];
// console.log("index2",index2,memo[needed],memo)
if (index2 != null) {
return [index2, i];
} else {
memo[nums[i]] = i;
}
}
}

explanation

  • The code defines a function called twoSum that takes in an array of numbers nums and a target number target.
  • The function uses an object memo as a hash table to store numbers as keys and their indices as values.
  • The function iterates over each element in the nums array.
  • For each element, it calculates the difference between the target and the current element and stores it in a variable called needed.
  • The function checks if needed exists as a key in memo.
  • If it does, the function returns an array containing the stored value (index of the first number) and the current index (index of the second number).
  • If needed does not exist in memo, the function stores the current number and its index in memo.
  • The function continues to iterate over the remaining elements in nums array.
  • If a pair of numbers that add up to the target is found, the function returns their indices in an array.
  • If no such pair is found, the function implicitly returns undefined.

Thanks for checking this out, I’m going to attend few interviews in the coming months and I want to share my learning with you.

Feel free to follow me Adarsh gupta

Buy me a coffee: https://www.buymeacoffee.com/Adarshgupta

--

--

Adarsh gupta

Software Engineer | JavaScript developer | Technical Writer . Work with me? adarshguptaworks@gmail.com Connect with me? twitter.com/adarsh____gupta/