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

To solve this problem in Javascript, we can use the hashing technique to store the indices of the numbers as we traverse through the array. We can use a hashmap to store the target difference and the index of its complement. If we find a number whose complement is already present in the hashmap, then we can return its indices.

Here's the implementation:

index.tsx
function twoSum(nums, target) {
  const hash = {};

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

    if (complement in hash) {
      return [hash[complement], i];
    }

    hash[nums[i]] = i;
  }
}

const nums = [2, 7, 11, 15];
const target = 9;

console.log(twoSum(nums, target)); // output: [0, 1]
340 chars
19 lines

In the above code snippet, we have defined a function twoSum that takes an array nums and an integer target as arguments. We have also defined a hashmap hash to store the indices of the numbers.

We then iterate through the array nums using a for loop and find the complement of the current number with respect to the target. If the complement is already present in the hashmap, we return its indices with the current index. Otherwise, we add the current number and its index to the hashmap.

At the end of the function, we call console.log with the function call twoSum(nums, target) to print the output. The output in this case is [0, 1], which means that the numbers at indices 0 and 1 add up to the target value of 9 in the input array.

gistlibby LogSnag