3
\$\begingroup\$

Here's my recursive implementation of a sliding window algorithm to find the longest substring of a given string without repeating characters. Is there a more idiomatic-Elixir way to write this?

defmodule MyString do
  def length_of_longest_substring(string), do: string |> length_of_longest_substring(0, 0, 0, %{})

  defp length_of_longest_substring(string, start_index, end_index, longest, indexes) do
    if end_index >= String.length(string) do
      longest
    else
      currrent_char = String.at(string, end_index)
      previous_occurrence = Map.get(indexes, currrent_char, -1)
      updated_indexes = Map.put(indexes, currrent_char, end_index)

      cond do
        previous_occurrence >= start_index ->
          string |> length_of_longest_substring(previous_occurrence + 1, end_index, longest, updated_indexes)

        true ->
          longest = max(longest, end_index - start_index + 1)

          string |> length_of_longest_substring(start_index, end_index + 1, longest, updated_indexes)
      end
    end
  end
end
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.