DEV Community

Discussion on: Daily Challenge #63- Two Sum

Collapse
 
aminnairi profile image
Amin

JavaScript

Recursive solution.

"use strict";

const addWith = target => current => target + current;
const equalsTo = target => current => target === current;

function twoSum(numbers, sum, index = 0) {
    if (numbers.length === 0) {
        return null;
    }

    const [first, ...rest] = numbers;

    const foundIndex = numbers.map(addWith(first)).findIndex(equalsTo(sum));

    if (foundIndex > 0) {
        return [index, foundIndex + index];
    }

    return twoSum(rest, sum, index + 1);
}

console.log(twoSum([18, 7, 1, 6, 0, 15, 3, 12, 111, 1111], 4)); // [2, 6]

Try it online.