We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
Post 36
Hacker Rank 10 - Rotating Strings
Published on: 2025-06-09
Tags:
elixir, Blog, Side Project, Hacker Rank
For this one we need to for the length of a given string swap the first letter to the last letter and keep track of each iteration.
Input:
5
abc
abcde
abab
aaa
z
Output:
bca cab abc
bcdea cdeab deabc eabcd abcde
baba abab baba abab
aaa aaa aaa
z
This is pretty simple to do each step it was just a matter of keeping track of the data types that we need for each step.
Since this is all about the data types I will go over all the steps until we get to the final print stage.
def read do
[_number | lists] =
IO.read(:stdio, :all) # String with "/n" .
|> String.split("\n") # List of strings with " ".
|> Enum.map(&String.split(&1, " ")) # List of list of strings.
|> List.flatten() # List of strings
# I don't need the number of cases so that is why I just return the list.
lists
end
This is just getting us to the list of strings.
defp rotate(string) do
string
|> String.graphemes() # Turns into a list of characters
|> head_to_tail() # See below
|> List.to_string() # Back into a String
end
defp head_to_tail(string) do
[head | tail] = string # Takes the list of characters and pops out the first one
[tail | head] # Appends the first character to the end
end
These are my helper functions that will take a strings and rotate the first letter to the last position.
Now we have the ability to take what we have above and turn it into a single function that will iterate over the list of strings.
def string_loop(strings) do
Enum.map(strings, fn string -> # Takes each string and performs the below
0..String.length(string) - 1 # Finds the string length
|> Enum.reduce([], fn # Iterates for the length of the string
_, [last | _rest] = lists -> # Every other case will take the last iteration and rotate
[rotate(last) | lists]
_, [] -> # First case as we will start with an empty list
[rotate(string)]
end)
|> Enum.reverse() # It will be in reverse order so we need to reverse
end)
end
At this point we should have a list of lists of strings. Remember that we need to print all the strings for a string given on the same line. Simple and concise approach to this problem.