Exercise: Runs

Run-length encoding squashes repeated characters: "aaabccdddd" becomes "a3b1c2d4". It is a favourite interview question because it tests a loop with state, and the bug almost everyone writes first: forgetting the last run when the loop ends.

Exercise: finish encode. For each run of the same character, write the character and then the length of the run. An empty string gives "". Runs can be long, so "z" * 12 gives "z12".

Keep track of the current character and how many times you have seen it. When the character changes, write out the run and start a new one.

Aim for one pass over the string. Building a list of pieces and joining them at the end is the idiom. The speed test checks that your code is linear.

Press Check to run the tests.