Skip to content Skip to sidebar Skip to footer

Find Indexes Of Elements In An Array Equal To Sum - Javascript

I am trying to find the indexes of element in an array equal to a specified sum. I only want 2 indexes. I am able to print the numbers but not the indexes. Please advice

Solution 1:

Use your hash table to store the indices instead of the values. Also, push the indices in your result array:

functionsumArrayHashTable(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]]

Solution 2:

functionsumArrayHashTable(arr, sum) {
  var result = [];
  for (var i = 0; i < arr.length; i++) {
    var test = 0;
    for (var j = 0; j < arr.length; j++) {
      if (i === j) {
        continue ;
      }
      test = arr[i] + arr[j];
      if (test === sum) {
        result.push([i, j]);
      }
    }  
  }
  return result;
}

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

Result will be [[2,4], [5,6]] plus [[4,2], [6,5]] you can take it from now

alghorithm is simple, O(n^2) - loop over array once, then again and find sum that equals 9

Post a Comment for "Find Indexes Of Elements In An Array Equal To Sum - Javascript"