Home > Enterprise >  Problem in returning indices of two numbers in array
Problem in returning indices of two numbers in array

Time:12-04

I have this problem:

Given an array of integers nums and an integer target, return the indices of two numbers that add up to target.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0]   nums[1] == 9, we return [0, 1].

With the code below was able to get the values added in array using set and Map

What I need help is to return the indices

const arr = [{key1: 2}, {key1: 7}, {key1: 11}, {key1: 15}];
const k = 9;
const valueSet = new Set(arr.flatMap((x) => Object.values(x)));
const valueArray = [...valueSet];

valueArray.forEach((v1, i1) => {
    for (let i2 = i1   1; i2 < valueArray.length; i2  ) {
        if ((v1   valueArray[i2]) === k) {
            // Return the indices
            return valueArray[i2];
        }
    }
});

CodePudding user response:

You have to parse and find the combination of indexes which gives you the sum.

Below code will help you

const arr = [{ key1: 2 }, { key1: 7 }, { key1: 11 }, { key1: 15 }];
const k = 9;
let valueSet = new Set(arr.flatMap((x) => Object.values(x)));
let valueArray = [...valueSet];

let indices;
let isFound = false;
// valueArray.forEach((v1, i1) => {
for (let i1 = 0; i1 < valueArray.length && !isFound; i1  ) {
  for (let i2 = i1   1; i2 < valueArray.length && !isFound; i2  ) {
    if ((valueArray[i1]   valueArray[i2]) === k) {
      //Return the Indices
      indices = [i1, i2];
      isFound = true;;
    }
  }
}
console.log(indices);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

The answer provided by Nitheesh works well. As for an explanation as to why your initial approach was not successful:

Using forEach to iterate over an array is different than using traditional for loops, in that the callback function is called for every element on the array. Using return in a forEach loop just breaks out of that particular element's callback, but not the entire iteration (hence, a return in a forEach loop behaves similarly to a continue in a for (...) loop.

You can read more about it here.

CodePudding user response:

First you need to get the array with the values from your array with keys [{key1: 2},{key1: 7},{key1: 11},{key1: 15}];. Then you loop the value array and return the index if the condition (nums[i] nums[j] == target) => (7 2 == 9) is true.

const arr = [{key1: 2},{key1: 7},{key1: 11},{key1: 15}];
const k = 9;
nums = arr.map((o) => {
  return Object.values(o)[0]
})

const twoSum = (nums, target) => {
    for(let i = 0; i < nums.length; i  ){
        for(let j = i 1; j < nums.length; j  ){
            if(nums[i]   nums[j] == target){
                return [i, j]
            }
        }
    }
};

console.log(twoSum(nums, k))
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Maybe this should do it:

function indice1(target, arr) {
  let result = [];

  for (let i = 0; i < arr.length; i  ) {
    for (let j = 0; j < arr.length; j  ) {
      if (arr[i]   arr[j] === target) {
        return (result = [arr[i], arr[j]]);
      }
    }
  }

  return result;
}

function indice2(target, arr) {
  let result = [];

  for (const i of arr) {
    for (const j of arr) {
      if (i   j === target) {
        return (result = [i, j]);
      }
    }
  }

  return result;
}

function indice3(target, arr) {
  return arr.reduce((acc, curr, i, arr) => {
    let result = [...acc, curr];

    for (const i of acc) {
      if (i   curr === target) {
        result = [i, curr];
        arr.splice(1);
        break;
      }
    }

    return result;
  }, []);
}

CodePudding user response:

const arr = [{ key1: 2 }, { key1: 7 }, { key1: 11 }, { key1: 15 }];
const k = 9;
let valueSet = new Set(arr.flatMap((x) => Object.values(x)));
let valueArray = [...valueSet];

valueArray.forEach((v,ind) => {
    let ind2 = valueArray.findIndex(iv => iv === k - v)
    ind2 > -1 && console.log([ind,ind2])
})
  • Related