Two Sum

June 22nd, 2022

#cs fundamentals, #array

NOTES:
Problem Statement: Given an array and a target integer, return the indecies of the two elements which sum to the target. Assuming the array has exactly one solution.
1
2
3
4
5
6
7
8
9
10
11
12
/** * @param {number[]} nums * @param {number} target * @return {number[]} */ var twoSum = function (nums, target) { const map = {}; // val: index for (var i = 0; i < nums.length; i++) { const n = nums[i]; const diff = String(target - n); if (map[diff] !== undefined) { return [map[diff], i]; } map[n] = i; } };