Solved a leetcode problem but not sure if its the right approach

Solved squares of a sorted array problem with Erlang :array module and a two pointer solution but not sure its a functional thing to do.

Thanks! :smiley:

  @spec sorted_squares(nums :: [integer]) :: [integer]
  def sorted_squares(nums) do
    arr = :array.from_list(nums)
    aux(arr, [], 0, :array.size(arr) - 1)

  defp aux(_, accum, left, right) when left > right, do: accum

  defp aux(arr, accum, left, right) do
    left_num = :array.get(left, arr) |> Integer.pow(2)  
    right_num = :array.get(right, arr) |> Integer.pow(2)

    case left_num > right_num do
      true -> aux(arr, [left_num | accum], left + 1, right)
      false -> aux(arr, [right_num | accum], left, right - 1)

You can build an easier and more idiomatic solution with these functions from the Enum module

and pipes: Pipe Operator ยท Elixir School

try to fill the gaps.

> [-4,-1,0,3,10] |> Enum._______ |> Enum._______
[0, 1, 9, 16, 100]
1 Like