The task is to find two numbers that sum to 0 and return their indices, given an array of integers.
The boilerplate code:
function findTwo(arr) {
// your code here
}
The array is scanned through once, while keeping track of every character seen
const map = new Map();
For each number x, check if -x has been seen before. If yes, return both indices.
for(let i = 0; i < arr.length; i++) {
const complement = -arr[i];
if(map.has(complement)) {
return [map.get(complement), i];
}
map.set(arr[i], i)
}
If no pairs sum to 0, return null.
The final code
function findTwo(arr) {
// your code here
const map = new Map();
for(let i = 0; i < arr.length; i++) {
const complement = -arr[i];
if(map.has(complement)) {
return [map.get(complement), i];
}
map.set(arr[i], i)
}
return null;
}
That's all folks!
Top comments (0)