skip to Main Content

Can anyone tell me why when I call the function, I’m getting undefined. I can access the result inside of the function but not outside.

function twoSum(nums, target) {
    console.log(nums); // keep track of user input.
    console.log(target); // keep track of target.

    let arrayOfIndices = [];

    // loop through array and perform addition operation
    for (let i = 0; i < nums.length; i++) {
        for (let j = i + 1; j < nums.length; j++) {
            if (nums[i] + nums[j] === target) {
                arrayOfIndices.push([i, j]);
            }
        }
    }

    if (arrayOfIndices.length === 0) {
        console.log("No two sum exists");
    } else {
        console.log(arrayOfIndices);
    }
    let result = arrayOfIndices;
    console.log(result);
}

// Test case
console.log(twoSum([3, 4, 5], 7));

2

Answers


  1. You need to add return result to the last line of your function. It’s not returning anything.

    Login or Signup to reply.
  2. This looks like a LeetCode problem (Two Sum). You over-complicating this because your algorithm is taking O(n^2) time. It also does not short-circuit (early return), so you are computing all the sums for every number in the array.

    As others have already mentioned, you will need to return the array of indices in your function. You did not do that. I do not see return arrayOfIndices nor do I see return result anywhere in that function.

    Just store the remainder in a map where the needed value (compliment) is a value you have yet to encounter. Once you have the compliment, return it’s index; along with the stored remainder’s index.

    /**
     * Given an array of integers nums and an integer target, return indices
     * of the two numbers such that they add up to target.
     * @param {number[]} nums - array of integers
     * @param {number} target - target sum
     * @return {number[]} indices of the two numbers where sum is the target.
     */
     const twoSum = (nums, target) => {
      let remainderMap = new Map();
      for (let i = 0; i < nums.length; i++) {
        let diff = target - nums[i]; // complement -> index
        if (remainderMap.has(diff)) {
          return [i, remainderMap.get(diff)]; // Return early
        }
        remainderMap.set(nums[i], i);
      }
    };
    
    const
      arr = [3, 4, 5],
      target = 7,
      indices = twoSum(arr, target);
      
    console.log(`${arr[indices[0]]} + ${arr[indices[1]]} = ${target}`);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search