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.
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
JavaScript
Recursive solution.
Try it online.