Skip to content

Instantly share code, notes, and snippets.

@coproduto
Last active February 15, 2023 18:46
Show Gist options
  • Save coproduto/c60ab42ebdef2c06d1abb0e0b2cdb710 to your computer and use it in GitHub Desktop.
Save coproduto/c60ab42ebdef2c06d1abb0e0b2cdb710 to your computer and use it in GitHub Desktop.
defmodule LongestCommonPrefix do
@spec run([String.t()]) :: String.t()
def run(strings) do
strings
|> Stream.map(&String.graphemes/1)
|> Stream.zip_with(&Function.identity/1)
|> Stream.take_while(&all_same?/1)
|> Stream.map(&hd/1)
|> Enum.join()
end
@spec all_same?([String.t()]) :: boolean()
def all_same?([char | chars]) do
Enum.all?(chars, &(&1 == char))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment