Solving the classic “aaaabbbcca” coding challenge

Photo by @joshuaryanphoto on Unsplash.

I’ve seen many versions of this problem in coding interviews, so I decided to solve it here, just for fun.

The problem goes like this:

Write a function that converts the input to the output

One important thing to note here is that the input can have the same letter in different groups, making the solution a little bit tricky if, for example, you try to use dictionaries.

Here is my proposed solution:

Pay attention to the line with, that gives us the ability to use a hash with duplicated keys.

You can read the algorithm like this:

# # If the current letter is equal to the previous one, increase the counter# # If the current letter is different to the previous one,
# # save the key (the letter) with the value (the counter) in the hash,
# # and then reset the counter.
# Return the hash

But calling that function, the output would look a little bit different than required.

Output:   {"a"=>4, "b"=>3, "c"=>2, "a"=>1}
Expected: [("a", 4), ("b", 3), ("c", 2), ("a", 1)]

I would ask the interviewer if she is ok with the output or if the format is a hard requirement, and she wants me to implement it. In that case, I would do something like this:

puts format_output(count_in_a_row("aaaabbbcca"))Output:   [("a", 4), ("b", 3), ("c", 2), ("a", 1)]
Expected: [("a", 4), ("b", 3), ("c", 2), ("a", 1)]

You can find the source code of this post here.

I do Management and Infrastructure Engineering.