freewebwithme
I see two solution from others
- using
Enummodule
@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
- 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.
Trending in Challenges
Other Trending Topics
I am happy to introduce the very α version of the new programming language compiled to BEAM.
Welcome Cure.
It has literally three kille...
New
Hobbes is a low-level distributed database for the Elixir programming language.
Hobbes provides a simple, safe, and scalable storage lay...
New
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve.
They are GUI (Emerge) and State management (S...
New
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
There are three potential reasons for members of this forum to have a look at https://vutuv.de
You are tired or annoyed of LinkedIn.
Yo...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #blog-post
- #elixir-ls
- #ai
- #elixirconf-us
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming










Showing Posts 1 to 1- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
Eiji
In a second example this part:
is adding you one extra loop over whole
numslist. You can passias a fourth argument tohelper/3function and work with it similarly to how you do that in anEnum.reduce_while/3-based example.