# TwoSum problem on LeetCode.com

Hey guys, so I’m trying to solve this problem:

Here’s the code I’m using:

``````var twoSum = function(nums, target) {
for(var i = 0;i < nums.length;i++){
if(nums[0] + nums[i] === target){
return ;
}
}
};
``````

I’m not sure how to return the indices of the array that gives the target value.

Thanks in advance for the help

Regards
Ma3_stro

In your code the indices are the values of `i`. In your code, you are comparing the sum of the first element and the other elements in the array with the target argument. I doubt it will get you to the solution you seek because the value of target might be equal to the sum of the second element and the third element, third element and fifth e.t.c

you need to return an array of indeces, so in this case you would return `[0, i]` as those are the indexes in the two numbers you are checking (`num[0]` and `num[i]`)

but you need to make your function check all the possible combinations inside the array, not only those with the number at index 0

So I should maybe change the if statement to something like this?

`nums[i] + nums[i + 1] === target`

If I may ask, how would you check all possible combinations in the array? I’m really new to JS so I’m still a bit shaky with how the arrays work.

I would suggest

``````var twoSum = function(nums, target) {
const len = nums.length;
for(let i = 0; i < len; i++){
// Below is a loop from i + 1 upto the last element
for(let j = i + 1;  j < len;  j++){
//Check for the condition here    i.e. if(nums[i]  +  nums[j] === target
}

}
};
``````

Ok I’ll try it but when it comes to returning the specific indices what should I enter to get them ?
Maybe something like this?
`return nums[i] + nums[j];`

You return `[i, j]`. `i` and `j` are the indices. `nums[i]` and `nums[j]` are the values at index `i` and `j` respectively.

do you understand why I said this here? can you apply this to your new code?

YESSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS, it finally works! Thanks so much man (I’ve been struggling with this for 2 days,lol)

1 Like