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

2 Answers

0 votes
let twoSum = function(arr: number[], target: number) {
    for (let i: number = 0; i < arr.length; i++) {
        for (let j: number = 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: number[] = [1, 5, 7, 4, 3, 2];
const result: number[] = 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: number[], target: number) {
    const indicies = {} as any;
   
    for (let i: number = 0; i < arr.length; i++) {
        const num: number = 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: number[] = [1, 5, 7, 4, 3, 2];
const result: number[] = twoSum(array, 9);
console.log(array[result[0]]);
console.log(array[result[1]]);
  
  
  
  
/*
run:
  
[1, 3] 
[0, 4] 
5 
4 
  
*/

 



answered Jul 17, 2023 by avibootz
...