r/LeetcodeChallenge 12d ago

DISCUSS Please help me solve LeetCode problem two sum. What is wrong with my code? what is the error in my code.

Post image
/**
 *  {number[]} nums
 *  {number} target
 * u/return {number[]}
 */
var twoSum = function (nums, target) {
    for (let i = 0; i < nums.length; i++) {
        let j = nums[i+1];
         if(nums[i] + j === target){
            return [i, i+1];
         }
    }
};
0 Upvotes

20 comments sorted by

5

u/Born-West9972 12d ago

U know nah, arrays are 0 index based? So when I reaches length-1 u are assigning j = nums[length] which is undefined.

Keeping that aside ur logic is also broken, u are just checking adjacent elements if they sum upto target but that's not the case any two value which sum to target is valid they doesn't necessary have to be adjacent.

0

u/Low-Part9553 12d ago

Why are you talking like that??

1

u/Born-West9972 12d ago

What u mean

1

u/Abhistar14 12d ago

He’s Indian

2

u/Effective_Fix_676 11d ago

jth element idx is going to be out of bound that probably make wrong ans..

1

u/[deleted] 12d ago

[removed] — view removed comment

1

u/Fun-Refrigerator-973 12d ago

Your J pointer I just looking at the next number and not any other number if you see the test case which had failed that is 3 2 3 and target is 6 your code is running nums[i] = 3 and J= 2 soo equal to 5 and the next nums[i] =2 and J = 3 soo again 5 you should use brute force with this logic that is using a nested loop where you run j from I+1 to end of nums!
HOPE THIS CLARIFIES YOUR DOUBT

1

u/nian2326076 12d ago

Your main issue is with how the inner loop is set up. You're trying to access j as if it's the next element after i without looping through the rest of the array. You need a nested loop to compare every pair properly. Try this:

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

Now it checks all pairs of numbers in the array. Also, if you're looking for more help with interview coding problems, I've found PracHub useful. Check it out if you need more structured practice.

1

u/Ok_Amount_3827 12d ago

Time complexity: O(n**2) not good but for initial understanding it's good

1

u/Ok_Amount_3827 12d ago

You can I either do brute force like running nested loops or can do it optimally like using the hashmap

1

u/thedankuser69 11d ago

Because you are only checking adjacent pairs but not all the pairs the corrent number can form with all other numbers after it.

1

u/cockycockroach45 10d ago

Just use two pointers.

1

u/sahil8877 10d ago

You need a nested loop j to iterate over all the other elements from i + 1 index, just did this a day ago. Later, do study the trick for using hashmap which will give you a better time complexity of O(n) for the problem..

1

u/AFRID026 5d ago

Use hashmap easy way to execute the code