Ctrl K

Run-Length Code Capped at Nine

Medium
The string text has to be squeezed before it goes down a slow link. The encoder reads it left to right and cuts it into blocks: each block is a run of identical consecutive letters, but no more than nine of them. A block is always taken as long as possible: it ends when the letter changes or when it already holds nine letters. Each block is written as two characters: its length (a single digit from 1 to 9) followed by the letter itself. The blocks are written one after another in order. Return the encoded string. For example, ten a's in a row turn into 9a1a.
Example 1
text='zzzyx' → '3z1y1x'

The three z's become "3z", then the single y and x become "1y" and "1x".

Example 2
text='kkkkkkkkkkkkm' → '9k3k1m'

Twelve k's don't fit in one block: first "9k", then the remaining three as "3k", and finally "1m".

Example 3
text='q' → '1q'

A single letter is a single block, "1q".

Constraints
  • 1 ≤ len(text) ≤ 2·10⁵
  • text consists of lowercase English letters only
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLongest Repeat-Free Stretch MediumLongest Mirror Fragment MediumReading a Zigzag by Rows MediumLenient Number Reader MediumNumber in Roman Numerals Medium
loading Python…
Input
text='zzzyx'
Expected
'3z1y1x'

Run checks the first 3 tests in your browser. Submit checks all 27 tests on the server, hidden ones included.