< Back to Data Structures and Algorithms
Blind 75 · LeetCode 1 · Arrays
Two Sum (Blind 75)
Two Sum again, written fresh for the Blind 75 list: the same one-pass lookup of each number's complement.
Step through it
Examples
Edge cases
- 20
- 71
- 112
- 153
target = 9
Step 0 of 2
Output
Running… play or step to the end.
The code
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
const twoSum = (nums, target) => {
const indicies = [];
const previousValues = {};
if (!nums || target == null) {
return indicies;
}
for (let i=0; i < nums.length; i++) {
const value = nums[i];
const compliment = target - value;
if (previousValues[compliment] !== undefined) {
indicies.push(previousValues[compliment], i);
break;
}
previousValues[value] = i;
}
return indicies;
};