Skip to Content

Run length

Level A. Teaches runs() and building a Str with interpolation.

You are given a word of lowercase letters, at most 10⁵ long. Replace each maximal run of equal letters by the letter and the run's length. For aaabcc print a3b1c2.

Input: the word. Output: the encoded word.

InputOutput
aaabcca3b1c2
5 tests · Ctrl+Enter
Hints
  • s.runs() walks each maximal stretch of equal letters as a slice of s: r.first! is its letter and r.len its length.
  • "{r.first!}{r.len}" turns the letter and the count into text; integers have no .to_str().
  • "".join(...) on [... for r in s.runs()] glues the pieces together, and the whole scan is O(n).
  • Strings and output covers Str, Char and interpolation.