Run-Length Encoding
Medium · 50 XPCompress a string so aaabccddd becomes a3b1c2d3, then write the decoder and prove it round-trips.
a3b1c2d3 aaabccddd True
Walk the string tracking the current character and a count; flush when it changes. For decode, pair each letter with the digits that follow it.
def encode(s):
out = ""
count = 1
for i in range(1, len(s) + 1):
if i < len(s) and s[i] == s[i - 1]:
count += 1
else:
out += s[i - 1] + str(count)
count = 1
return out
def decode(s):
out = ""
i = 0
while i < len(s):
ch = s[i]
j = i + 1
while j < len(s) and s[j].isdigit():
j += 1
out += ch * int(s[i + 1:j])
i = j
return out
text = "aaabccddd"
print(encode(text))
print(decode(encode(text)))
print(decode(encode(text)) == text)
Run your code to check it…
How to approach Run-Length Encoding
Encoding walks the string and watches for the character to change. Keep a count for the current run; when the next character differs (or the string ends), write the character and its count, then start a new run at 1.
Decoding reverses it: read a letter, then read all the digits that follow it, because a run of twelve is "a12", not "a1" and "2". Multiply the letter by that number. Proving the round trip with decode(encode(text)) == text is the real test.
Worked through on this data
- "aaabccddd": three a's give a3, one b gives b1.
- Two c's give c2, and three d's, flushed when the string ends, give d3: a3b1c2d3.
- Decoding reads a and 3, b and 1, c and 2, d and 3, rebuilding "aaabccddd". The comparison prints True.
Common mistakes
- Forgetting to flush the final run, so the encoding ends at c2 and the d's vanish.
- Decoding one digit at a time, which turns "a12" into "a" followed by a stray "2".
- Input that already contains digits, such as "a1", makes the encoding ambiguous. Real formats escape digits or store counts in a separate byte.
Time and space
Both directions are one pass: O(n) time. Build the result in a list and join it at the end to keep the space O(n) without repeated copying.
Where this shows up
Run-length encoding is inside fax machines, BMP and TIFF images, and the first stage of many compression schemes. It shines on data with long runs and makes random data bigger.
Take it further
Write the encoder as a one-liner with itertools.groupby, which yields each character together with its run.