Run Length Encoding
February 9, 2021
Alexey Grigorev says:
Most candidates cannot solve this interview problem:
Input: “aaaabbbcca”
Output: [(“a”,4), (“b”,3), (“c”,2), (“a”,1)]
Write a function that converts the input to the output. I ask it in the screening inverview and give it 25 minutes. How would you solve it?
Your task is to write the requested function. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
First thing that came to mind. In Ruby.
Output:
Here is a short and simple solution in standard R7RS Scheme using fold
from SRFI 1.
Output:
Racket has splitf-at the same as split-while in your Prelude and I like :
Interesting drill. Although I don’t find RLE a serious contender when it comes to compression algos, it’s a fun exercise. Here is my take on it in Julia 1.5: https://pastebin.com/3hiUsc4v
Cheers
Here’s a solution in Python.
Output:
Here’s a Haskell version.
A solution in Racket:
Example:
Here’s are two solutions in C. The first streams the output while looping over the input string. The second creates an intermediate array with the character counts.
Example usage (same for both programs):