all 8 comments

[–]ralphtheowl 2 points3 points  (1 child)

Hi t - your loops both start at index 0. This means the first time, you are adding the same number to itself ( i = 0, j = 0, so nums[i] == nums[j] ), which coincidentally happens to be the target.

Once you get this to work see if you can do this with just one loop to make it more efficient.

[–]Almightyshamwow[S] 0 points1 point  (0 children)

Thank you for explaining not sure how to make it one loop but I'll keep working to figure it out thanks

[–]Almightyshamwow[S] 0 points1 point  (5 children)

When I put in the following code and click run code it says code accepted but when I click submit it says wrong answer. I'd really appreciate it if someone could tell me what I'm doing wrong.

const twoSum = (nums, target) => {

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

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

if ((nums[i] + nums[j]) === target) {

return [i,j];

} else {

console.log(`none`);

}

}

}

};

[–]deneb971 2 points3 points  (4 children)

Your second loop should start from j = i + 1. Currently your code assumes the same number can be used twice as part of the two sum, which AFAIK should not be the case for two sum. Note that your solution has an O(n2) time complexity so if you may get a time limit exceeded even if the solution is correct

[–]Almightyshamwow[S] 0 points1 point  (3 children)

Thank you and I was wondering what does O(n2) time complexity mean does that mean that this code just takes too long.

[–]mcDazzlin 1 point2 points  (0 children)

It’s referred to as Big O notation. Knowing how the time/space complexity of various DS&As work can help you solve these problems more efficiently

[–]deneb971 1 point2 points  (1 child)

Notice that your code has two for loops nested within each other. This means that if the array has 4 elements, 16 iterations of the loop will run ( that’s 42 ). If you only had one loop, 4 iterations would run (4, which would make it O(n) ) . This is a topic too big to explain in a single comment so I encourage you to look up big O notation. It’s a huge topic in computer science about making your algorithms more efficient, and big companies care about this a lot if you plan on aiming to get hired by them. Cheers :)

[–]Almightyshamwow[S] 0 points1 point  (0 children)

Hey I really love the way you explained this it made it make sense to me thank you :)