JavaScript Leet Code: Two Sum

In this article we will see how to compare the sum of two elements of an array with a total in JavaScript.

We have to solve the following exercise: given an array of integers and a total, we need to return an array containing the first two numbers contiguous which, added together, correspond to the total.

This is a useful opportunity to rediscover the while loop. It involves incrementing the internal counter twice, the first time to get the current number and the second for the next number.


'use strict';

const twoSum = (nums = [], target = 0) => {
    if(nums.length === 0) {
        return [];
    }
    if(nums.length === 1) {
        return nums[0] === target ? [0] : [];
    }

    const output = [];
    let i = -1;

    while(i < nums.length - 1) {
        i++;
        let sum = nums[i] + nums[i + 1];
        if(sum === target) {
            output.push(i);
            output.push(i + 1);
            break;
        }
    }

    return output;
};

console.log(twoSum([2,7,11,15], 9)); // [2,7]
Back to top