Skip to content
BytePatterns

String Compression

Strings: lesson 10 of 11

One read cursor, one write cursor, no second string.

Lesson 10 of 11 · 5 min

String Compression

Step 1 of 8

A run of identical characters becomes the character and its count — and it is written into the same buffer.

The Idea

Run-length coding replaces a stretch of identical characters with the character and how many there were. Done in place it needs two cursors: read walks the runs, write lays the output down behind it. The write cursor can never catch up, because two characters are only ever replaced by two or fewer. Runs of one stay bare, and a count above nine is written one digit at a time.

Real-World Example

A screen recorder storing a row of identical pixels as "this grey, 240 times". The frame shrinks hard on flat backgrounds, nothing is lost, and the decoder just repeats what the count says.

The Code

def compress(chars):
    write = read = 0
    while read < len(chars):
        c, run = chars[read], 0
        while read < len(chars) and chars[read] == c:
            read += 1                 # measure the whole run first
            run += 1
        chars[write] = c
        write += 1
        if run > 1:                   # a run of one stays bare
            for d in str(run):
                chars[write] = d
                write += 1
    return write, chars[:write]

print(compress(list("aabbc")))   # (5, ['a', '2', 'b', '2', 'c'])

Python

Your turn

Put the steps in the right order.

  1. Write the run length, one digit per slot, if the run is longer than one
  2. Write the character at the write cursor
  3. Advance the read cursor to the end of the run of equal characters
  4. Note the character under the read cursor

Mini quiz

1 / 3

Why can the write cursor never overtake the read cursor?

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.