Algorithms · Visualized
Compression: Run-Length
Compression & Encoding
Shrink data with runs, frequencies, and clever codes.
A simple compression technique that replaces consecutive repeated characters with a single character plus a count. Time: O(n) average, O(n) worst; space: O(n) — output storage (can be smaller or larger than input depending on repetition).
Big-O: Huffman gives prefix-free optimal codes.
Run-Length Encoding
Compression / EncodingA simple compression technique that replaces consecutive repeated characters with a single character plus a count. For example, 'aaabbc' becomes 'a3b2c1'. It works best on data with lots of repeated runs, like simple images or repetitive text.
How Run-Length Works
- Start at the beginning of the input, tracking the current character and a count of 1.
- Move through the input character by character.
- If the next character matches the current one, increment the count.
- If it's different, write out the current character and its count to the output, then reset the current character to this new one with a count of 1.
- After reaching the end of the input, write out the final character and its count.
Run-Length Worked Example
Input: aaabbbcccd
'a' repeats 3 times → write 'a3'. 'b' repeats 3 times → write 'b3'. 'c' repeats 3 times → write 'c3'. 'd' appears once → write 'd1'. Encoded output: 'a3b3c3d1'.
def encode(s):
out = []
i = 0
while i < len(s):
j = i
while j < len(s) and s[j] == s[i]:
j += 1
out.append(f"{s[i]}{j - i}")
i = j
return ''.join(out)
def decode(s):
out = []
i = 0
while i < len(s):
ch = s[i]
i += 1
j = i
while j < len(s) and s[j].isdigit():
j += 1
out.append(ch * int(s[i:j]))
i = j
return ''.join(out)Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Run-Length Time & Space Complexity
When to Use Run-Length
- Compressing simple images with large blocks of the same color (e.g. fax transmission, basic bitmap compression).
- A building block or preprocessing step in more advanced compression pipelines.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.