Two Sum

Find indices of two numbers in an array that add up to a target value using a hash map for O(n) time complexity.

Code

Algorithms
const map = new Map();
let result = null;
for (let i = 0; i < arr.length; i++) {
  const complement = target - arr[i];
  if (map.has(complement)) { result = [map.get(complement), i]; break; }
  map.set(arr[i], i);
}
return result;

Parameters

Array of numbers

Target sum

Browser·fetch() may be limited by CORS

More JavaScript Snippets