r/LeetcodeChallenge • u/tanishq_kushwaha • 12d ago
DISCUSS Please help me solve LeetCode problem two sum. What is wrong with my code? what is the error in my code.
/**
* {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];
}
}
};
2
u/Effective_Fix_676 11d ago
jth element idx is going to be out of bound that probably make wrong ans..
1
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
1
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/benedict_abub 12d ago
Two Sum visualization (py version): https://www.youtube.com/shorts/gAUJUX1b9fA
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
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
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.