Two sum from leetcode

I see two solution from others

  1. using Enum module
@spec two_sum(nums:: [integer], target:: integer) :: [integer]
  def two_sum(nums, target) do
    Enum.reduce_while(nums, {%{}, 0}, fn n, {map, i} ->
       complement = Map.get(map, target - n)
       if complement do
         {:halt, [i, complement]}
       else
          {:cont, {Map.put(map, n, i), i + 1}}
       end
    end)
  end
  1. Using recursion
  @spec two_sum(nums :: [integer], target :: integer) :: [integer]
  def two_sum(nums, target) do
    helper(Enum.with_index(nums), %{}, target)
  end

  defp helper([{value, index} | _t], map, _target) when is_map_key(map, value), do: [map[value], index]
  defp helper([{value, index} | t], map, target), do: helper(t, Map.put(map, target - value, index), target)

What is difference in terms of efficiency?(time and space complexity)?
First solution is easy to understand for me but second solution using recursion is hard to understand.

In a second example this part:

is adding you one extra loop over whole nums list. You can pass i as a fourth argument to helper/3 function and work with it similarly to how you do that in an Enum.reduce_while/3-based example.

1 Like