two for loops in js. cannot work on nested for loop

759 views Asked by At

I'm working on a problem below, but not sure why my second for loop does console.log anything. I currently get a result, [], and when I work on loops I sometimes confused because the output returns empty result. So why my second for loop is not executed and why I'm not able to push the result to result array?

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.You may assume that each input would have exactly one solution, and you may not use the same element twice.You can return the answer in any order.

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

function a(nums, target) {

let result = [];

for (let i = 0; i < nums.length -1; i++){


    let firstNum = nums[i];

    console.log(i)
    
    for (let j = i + 1; j < nums.length -1; j++){

        console.log(j)
        let secondNum = nums[j];
        
        let sum = firstNum + secondNum;
        
        

        if (sum === target) {
            return result.push(i, j);
            }
        } 
    }
    return result; 
};

a([2,7,11,15], 9)
3

There are 3 answers

4
Vishal V On BEST ANSWER

Push return only the length of the array, try like below,

function a(nums, target) {

    let result = [];

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


        let firstNum = nums[i];

        console.log("i", i)

        for (let j = i + 1; j < nums.length; j++){

            console.log("j", j)
            let secondNum = nums[j];

            let sum = firstNum + secondNum;



            if (sum === target) {
                result.push(i, j);
                return result;
            }
        } 
    }
    return result; 
};

let result = a([2,7,11,15], 9);
console.log(result);
0
Didier J. Angel On

Your code is actually correct except for the fact that you are returning the result of result.push(i, j) which returns the length of the array.

Use result.push(i, j); and then return result;

Instead of just return result.push(i, j);

0
Mulan On

Consider breaking the problem down into smaller parts -

  • t generates unique combinations of numbers
  • a steps thru the generator searching for the first valid solution

function* t(n, i = 0, p = [])
{ if (p.length >= 2)
    yield p
  else if (i >= n.length)
    return
  else
    ( yield* t(n, i + 1, [...p, n[i]])
    , yield* t(n, i + 1, p)
    )
}

function a(n, q)
{ for (const [a, b] of t(n)) // <- step thru t
    if (a + b == q)          // <- simple condition
      return [a, b]          // <- solution
}

const result =
  a([2,7,11,15], 9)

console.log(result)

Output -

[2, 7]

a will return undefined if the answer cannot be reached