Editor

Run-Length Decoding

#277 · Codes and ciphers · Intermediate · 60 XP · about 10 min

Run-length encoding stores a run of repeated characters as a count followed by the character, so 12a3b means twelve as followed by three bs. A count can have several digits, and a character with no count in front of it appears once: x3yz stands for xyyyz.

Write rl_decode(s) that returns the decoded string. Any character that is not a digit can be encoded, spaces and punctuation included (digits themselves cannot, because they would be read as a count). Counts are at least 1 and have no leading zeros.

If s ends with a count that has no character after it, the encoding is broken: raise a ValueError.

Examples

rl_decode("12a3b")  # returns 'aaaaaaaaaaaabbb'
rl_decode("x3yz")   # returns 'xyyyz'
rl_decode("2 3!")   # returns '  !!!'
rl_decode("ab12")   # raises ValueError

In the third example the encoded characters are a space (twice) and an exclamation mark (three times).

Constraints

  • s has 0 to 10,000 characters.
  • The decoded string has at most 1,000,000 characters.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.