Home Posts Tags Post Search Tag Search

Post 29

Hacker Rank 05 - Prefix Conpression

Published on: 2025-05-27 Tags: elixir, Blog, Side Project, Hacker Rank
So for this challenge I need to find the similarities from 2 different strings and then output:
similarity_length similarity_string
difference_string_1_length difference_string_1
difference_string_2_length difference_string_2

Input
abcghf
abcdef

Output
3 abc
3 ghf
3 def

So for this I wanted to do a couple things but first I wanted to be able to go through the strings only once so I can avoid a timeout:

    defp find_similar([<<h1, t1::binary>>, <<h2, t2::binary>>]) when h1 == h2 do
        <<h1>> <> find_similar([t1, t2])
    end
      
    defp find_similar([_, _]), do: ""

So for this I wanted to use recursion, these functions above goes through each element and takes the more and more characters of the strings and tests them against each other. 
<<h1, t1::binary>> Extract the first byte (not necessarily a full Unicode character) from a binary, and bind the rest as another binary.

Then as we go through the rest of the string it will only grab more if they are equal characters. Other wise the base case is anything that doesn't match.

Once that was set I needed to find the rest of the strings that don't match to the beginning.

   defp find_else(string_1, string_2, prefix) do
        first = remove_prefix(string_1, prefix)
        second = remove_prefix(string_2, prefix)
        ["#{String.length(first)} #{first}", "#{String.length(second)} #{second}"]
    end

    defp remove_prefix(string, prefix) do
        String.replace_prefix(string, prefix, "")
    end

These will simply use the remove_prefix/2 to replace the beginning of the string with "" once that is done I need to then get them into the proper format for the output.

Once that is done we need to have some outer functions that will take the prefix and turn it into the proper format. 

    defp format_prefix(prefix) do
        "#{String.length(prefix)} #{prefix}"
    end

Then we put it all together and output the different lines. I'll leave that up to you.