This content originally appeared on DEV Community and was authored by Bukunmi Odugbesan
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!
This content originally appeared on DEV Community and was authored by Bukunmi Odugbesan
Bukunmi Odugbesan | Sciencx (2025-11-22T22:31:35+00:00) Coding Challenge Practice – Question 63. Retrieved from https://www.scien.cx/2025/11/22/coding-challenge-practice-question-63/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.