NazariyM
9/27/2019 - 4:52 PM

Find indexes of elements in an array equal to sum - Javascript

function sumArrayHashTable(arr, sum) {

  const result = [];
  const hashTable = {};

  for (let i = 0; i < arr.length; i++) {

    const S = sum - arr[i];

    if (hashTable[S] !== undefined) {
      result.push([i, hashTable[S]]);
    } else {
      hashTable[arr[i]] = i;
    }
  }

  return result;
}

console.log(sumArrayHashTable([5, 2, 6, 1, 3, 9, 0], 9));

//Result should be [[2,4], [5,6]]