How to optimize the following Javascript code mention

Advertisements

Below is the code I would like to optimise.
So, Question is that array in mention all value we need to check two value of sum is 8.
If, yes, then we need to find this value of index.

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

console.log(arr);
for (let i = 1; i <= arr.length; i++) {
  for (let j = 1; j <= arr.length; j++) {
    let cal = j + i;
    if (cal === sum && j !== i) {
      console.log(arr.indexOf(i));
    }
  }
}

>Solution :

Try this way

 const arr = [2, 3, 1, 4, 5];
    const sum = 8;
    const indices = {};

    for (let i = 0; i < arr.length; i++) {
      const complement = sum - arr[i];

      if (complement in indices) {
        console.log(`Indices ${indices[complement]} and ${i} add up to ${sum}`);
        break;
      }
      indices[arr[i]] = i;
    }

  

Leave a ReplyCancel reply