Just as an FYI for Leetcode: because passing a challenge is based on the execution speed, it’s unusual that a[ny naïve] recusive solution will work if you use JavaScript. It will work fine if you use Erlang or Elixir (and I assume Scala as well), but not for languages that don’t have the optimisations required to make recusion as performant as imperative looping.
So for example, here is a recursive solution, I think fine to post because it just will not pass (was hitting ~400ms before I got an out of memory error every time I tried to submit it). It works perfectly fine [given no time limit], but it’s no use in the context of Leetcode:
function twoSum ([head, ...rest], target, headIndex = 0) {
const sumIndex = rest.indexOf(target - head);
return (sumIndex !== -1)
? [headIndex, sumIndex + headIndex + 1]
: twoSum(rest, target, headIndex + 1);
}
Edit: exact same solution in Elixir, passes fine (not particularly efficient, but works every time I hammer submit):
defmodule Solution do
def two_sum([head|rest], target, head_index \\ 0) do
case Enum.find_index(rest, fn x -> x + head == target end) do
nil -> two_sum(rest, target, head_index + 1)
x -> [head_index, x + head_index + 1]
end
end
end
Edit edit: also fyi
You can have as many extra arguments as you want as long as the function can be executed with the expected number of arguments. So in practice, this means you normally initialise them with a default
function someChallenge(
requiredArg,
myOtherArg = "fine",
anotherArg = "also fine",
yetAnotherArg = "still fine"
) {
...