Compress and Decompress a Run-Length Encoded String
StringsAuto-graded · 19 test casesLast 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 inputsis 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 inputsis a valid RLE string produced by the encode rules above (counts ≥ 1). - An empty string
""in either mode should return"".
Constraints
modeis either"encode"or"decode".0 ≤ len(s) ≤ 2000- For
"encode"mode:scontains only ASCII letters (a–z,A–Z). - For
"decode"mode:sis 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.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem has two independent sub-problems that share the same function entry point.
Encoding
Walk through the string left-to-right, maintaining a count of how many times the current character has appeared consecutively. When the character changes (or the string ends), emit str(count) + character and reset the counter to 1. This single pass is straightforward and produces the canonical RLE form.
Why it is correct: Every maximal run is captured exactly once. The counter resets precisely at boundaries between different characters, so no run is split or merged.
Decoding
Use an index i that walks through the encoded string. At each step:
- Advance a second pointer
jwhile characters are digits, collecting the multi-character count token. - Convert
s[i:j]to an integer; the next characters[j]is the run character. - Append
char * countto the result, then seti = j + 1.
Handling multi-digit counts (e.g., "12a") is the only subtlety — the inner digit-scanning loop handles this naturally.
Edge cases
- Empty string: handled with an early return of
""for both modes. - Single character: encodes to
"1x", decodes back correctly. - Long runs (e.g., 20
'a's): encode produces"20a", decode must parse"20"as a two-digit integer.
Complexity
- Time: O(n) for both encode and decode, where n = len(s).
- Space: O(n) for the output string (unavoidable).
def rle_codec(s: str, mode: str) -> str:
if not s:
return ""
if mode == "encode":
result = []
count = 1
for i in range(1, len(s)):
if s[i] == s[i - 1]:
count += 1
else:
result.append(str(count) + s[i - 1])
count = 1
result.append(str(count) + s[-1])
return "".join(result)
else: # decode
result = []
i = 0
while i < len(s):
# collect digits
j = i
while j < len(s) and s[j].isdigit():
j += 1
count = int(s[i:j])
char = s[j]
result.append(char * count)
i = j + 1
return "".join(result)