Find the smallest sum of all indices of unique number pairs summing to a given number in JavaScript


We are required to write a function that takes in an array of numbers as the first argument and a target sum as the second argument. We then want to loop through the array and then add each value to each other (except itself + itself).

And if the sum of the two values that were looped through equals the target sum, and the pair of values hasn't been encountered before, then we remember their indices and, at the end, return the full sum of all remembered indices.

If the array is −

const arr = [1, 4, 2, 3, 0, 5];

And the sum is −

const sum = 7;

Then the output should be 11, because,

4 + 3 = 7
5 + 2 = 7

Index −

4 [index: 1]
2 [index: 2]
3 [index: 3]
5 [index: 5]

i.e.

1 + 2 + 3 + 5 = 11

Example

The code for this will be −

const arr = [1, 4, 2, 3, 0, 5];
const findIndexSum = (arr = [], sum = 0) => {
   let copy = arr.slice(0);
   const used = [];
   let index = 0, indexFirst = 0, indexSecond, first, second;
   while (indexFirst < copy.length){
      indexSecond = indexFirst + 1;
      while(indexSecond < copy.length){
         first = copy[indexFirst];
         second = copy[indexSecond];
         if (first + second === sum){
            used.push(first, second);
            copy = copy.filter(el => first !== el && second !== el );
            indexFirst--;
            break;
         }
         indexSecond++;
      }
      indexFirst++;
   };
   const indexSum = used.sort().reduce((acc, val, ind) => {
      const fromIndex = ind === 0 || val !== used[ind - 1] ? 0 : index + 1 index = arr.indexOf(val, fromIndex);
      return acc + index;
   }, 0);
   return indexSum;
};
console.log(findIndexSum(arr, 7));

Output

And the output in the console will be −

11

Updated on: 20-Nov-2020

78 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements