0

Given an array of integers and I want to return indices of the two numbers such that they add up to a specific target. Assuming that each input would have exactly one solution, and I haven't used the same element twice.

I am using the brute force approach to Loop through each element x and find if there is another value that equals to target−x

code snippet:

var twoSum = function(nums, target) {
        for(var i ; i<nums.length ; i++){
            for(var j = i + 1; j<nums.length ; j++){
                if (nums[j]==target-nums[i]){
               // This is where I want to return new array 
                    return 
                    
                }
                
            }
        }
        
    };

1
  • 1
    for(var i ; isn't going to work, you need to initialise i with a number value: for(var i=0;, otherwise you're trying to do ++undefined. You haven't actually said what the problem is or any errors you get.++undefined produces NaN, then ++NaN continues to produce NaN so i<nums.length is always false (since NaN < anything is always false. Commented Dec 18, 2017 at 5:49

1 Answer 1

1

You just want to return the two indices?

return [i, j];
Sign up to request clarification or add additional context in comments.

3 Comments

May be its an opinionated comment, but I guess this could have been a comment
is it appropriate if I use new Array(i,j);
Always prefer array literals [] to using the constructor in javascript. Same goes with objects. Use {} instead of new Object()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.