KatInterview

Compress and Decompress a Run-Length Encoded String

StringsAuto-graded · 19 test cases
EasyAuto-gradedStringsstringsencodingparsing

Last updated

Tests ability to implement both directions of run-length encoding: compressing a plain string into a compact form and expanding it back, handling edge cases carefully.

Run-Length String Codec

Run-length encoding (RLE) is a simple compression scheme where consecutive repeated characters are stored as a count followed by the character.

For example, the string "aaabbc" becomes "3a2b1c".

You must implement two operations on strings, selected by a mode parameter:

Mode "encode"

Convert a plain string into its RLE form:

  • For each maximal run of identical characters, output the count (as a decimal integer) followed by the character.
  • There are no separators between groups.
  • Example: "aabbbcccc" → "2a3b4c"

Mode "decode"

Convert an RLE string back into the original plain string:

  • The encoded string consists of alternating positive integer tokens and single characters.
  • Each integer token may be more than one digit (e.g., "12a" means twelve 'a's).
  • The integer is always immediately followed by exactly one character.
  • Example: "2a3b4c" → "aabbbcccc"

Implement the function:

def rle_codec(s: str, mode: str) -> str:

Notes

  • In "encode" mode the input s is a non-empty string of printable ASCII characters (printable, excluding digits so that the encoded form is unambiguous). Actually, the input to encode will only contain letters (a–z, A–Z).
  • In "decode" mode the input s is a valid RLE string produced by the encode rules above (counts ≥ 1).
  • An empty string "" in either mode should return "".

Constraints

  • mode is either "encode" or "decode".
  • 0 ≤ len(s) ≤ 2000
  • For "encode" mode: s contains only ASCII letters (a–z, A–Z).
  • For "decode" mode: s is a valid RLE string (alternating runs of digits then a single letter); all counts are ≥ 1.
  • No leading zeros appear in counts inside a valid encoded string.

Examples

Example 1

Input: rle_codec('aaabbc', 'encode')

Output: '3a2b1c'

Example 2

Input: rle_codec('3a2b1c', 'decode')

Output: 'aaabbc'

Example 3

Input: rle_codec('', 'encode')

Output: ''

Hints

Hint 1

For encoding, iterate through the string keeping a running count; when the character changes (or you reach the end), append the count and character to the result.

Hint 2

For decoding, use two pointers or a simple index: first advance past all digit characters to collect the count, then read the next character and repeat the pair.

Hint 3

Make sure your decode handles multi-digit counts like '12a' correctly — collect all consecutive digit characters before converting to int.