Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

116
Views
Two Sum Leetcode

I wrote the code, but for some reason it displays the index 1, 2, 3, while 3 + 4 will in no way be equal to target (6).

var twoSum = function(nums, target) {
   let sum = [];
   var n = 2;

    for(let i = 0; i < nums.length; i++) {
       for(let a = 1; a < nums.length; a++) {
           if(nums[i] + nums[a] == target) {
               sum.push(i);
               sum.push(a);
           }
       }
   } 
   let unique = sum.filter((e, i) => sum.indexOf(e) === i )
   return unique/* .slice(0, n); */
};
console.log(twoSum([1,3,4,2],6))

Input [1,3,4,2] 6

Output [1,2]

Expected [2,3]

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

As per my comment, start the inner loop at a = i + 1 to avoid summing numbers with themselves as well as to avoid checking the same combination twice, e.g (1, 2) and (2, 1):

var twoSum = function(nums, target) {
    let sum = [];
    let n = 2;

    for (let i = 0; i < nums.length; i++) {
        for (let a = i + 1; a < nums.length; a++) {
            if (nums[i] + nums[a] === target) {
                sum.push(i);
                sum.push(a);
            }
        }
    } 
    let unique = sum.filter((e, i) => sum.indexOf(e) === i )
    return unique/* .slice(0, n); */
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!