Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,987 questions

51,931 answers

573 users

How to implement the two sum algorithm to find two values in array that add up to target with JavaScript

2 Answers

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

console.log(twoSum([1, 5, 7, 4, 3, 2], 9))

console.log(twoSum([3, 1, 4, 2, 5], 8))

const array = [1, 5, 7, 4, 3, 2];
const result = twoSum(array, 9);
console.log(array[result[0]]);
console.log(array[result[1]]);




/*
run:

[1, 3]
[0, 4]
5
4

*/

 



answered Jul 16, 2023 by avibootz
edited Jul 16, 2023 by avibootz
0 votes
let twoSum = function(arr, target) {
    const indicies = {}
  
    for (let i = 0; i < arr.length; i++) {
        const num = arr[i];
        if (indicies[target - num] != null) {
            return [indicies[target - num], i];
        }
        indicies[num] = i;
    }
    
    return [-1, -1];
};

console.log(twoSum([1, 5, 7, 4, 3, 2], 9))

console.log(twoSum([3, 1, 4, 2, 5], 8))

const array = [1, 5, 7, 4, 3, 2];
const result = twoSum(array, 9);
console.log(array[result[0]]);
console.log(array[result[1]]);




/*
run:

[1, 3]
[0, 4]
5
4

*/

 



answered Jul 16, 2023 by avibootz
...