Find Indices of a Target Sum

by jacobwsmith

JavaScript

console.clear();

/* 
Given an array of numbers, return indices of the two integers such that they add up to a specific target.

You should assume that each input would have exactly one solution, and you may not use the same element twice.

Example:
Given numbers = [2, 7, 11, 15], target = 9,

Because numbbers[0] + numbers[1] = 2 + 7 = 9,
return [0, 1].
*/

const findIndices = function(numbers, target) {
  const map = new Map();
  for (var i = 0; i < numbers.length; i++) {
    let complement = target - numbers[i];
    if (map.has(complement)) {
      return [map.get(complement), i];
    }
    map.set(numbers[i], i)
  }
};

const isArrayEqualHelper = (a, b) => a.length === b.length && a.every((value, index) => value === b[index]);

// Tests should return true 😊
console.log(isArrayEqualHelper(findIndices([2, 7, 11, 15], 9), [0, 1])); // [0, 1];
console.log(isArrayEqualHelper(findIndices([2, 7, 11, 15], 17), [0, 3])); // [0, 3];
console.log(isArrayEqualHelper(findIndices([1, 2, 3, 4, 5, 6, 7, 8, 9], 6), [1, 3])); // [ 1, 3];
console.log(isArrayEqualHelper(findIndices([1, 2, 3, 4, 5, 6, 7, 8, 9], 10), [3, 5])); // [ 3, 5];