Skip to content

Run-length encoding

words

Level 1 of 3

Also called RLE.

how it works

The idea on aaabccdddd, as the watch page runs it.

A run is one letter, or the same letter several times in a row: aaab has runs aaa and b. Many texts have long runs, so write each run once: how many letters, then the letter. aaab becomes 3a1b. Making a text shorter like this is called compressing it. Read from the left. The first letter starts a run. Compare each next letter with the run's letter. The same, and the run grows. Different, and you write the run and start a new one. At the end, write the last run. This page counts comparisons, one for each letter after the first.

textcodecharacters
aaabccdddd3a1b2c4d8
xyzxyzxyzx1x1y1z1x1y1z1x1y1z1x20
zzzzzzzzzz10z3
aaabccdddd has 4 runs, so its code is 3a1b2c4d. Each text of 10 letters takes 9 comparisons, yet one code is shorter, one twice as long, and one tiny.
Runs of 3, 1, 2 and 4: 7 moments of its 11 steps, the steps between them left for the watch page
  1. step 1 of 11

    12345678910aaabccdddd

    The first letter, a, starts a run of 1.

    what it remembers to know where it is
    run's letter
    a
    run so far
    1

    watch from here

  2. step 3 of 11

    12345678910aaabccdddd

    The next letter is a too, so the run grows to 3.

    what it remembers to know where it is
    run's letter
    a
    run so far
    3

    watch from here

  3. step 4 of 11

    12345678910aaabccdddd3a

    The next letter, b, is not a. Write the run under its first letter: 3, then a. Then b starts a run of 1.

    what it remembers to know where it is
    run's letter
    b
    run so far
    1

    watch from here

  4. step 5 of 11

    12345678910aaabccdddd31ab

    The next letter, c, is not b. Write the run under its first letter: 1, then b. Then c starts a run of 1.

    what it remembers to know where it is
    run's letter
    c
    run so far
    1

    watch from here

  5. step 7 of 11

    12345678910aaabccdddd312abc

    The next letter, d, is not c. Write the run under its first letter: 2, then c. Then d starts a run of 1.

    what it remembers to know where it is
    run's letter
    d
    run so far
    1

    watch from here

  6. step 10 of 11

    12345678910aaabccdddd312abc

    The next letter is d too, so the run grows to 4.

    what it remembers to know where it is
    run's letter
    d
    run so far
    4

    watch from here

  7. step 11 of 11

    12345678910aaabccdddd3124abcd

    Done: write the last run, 4, then d. The code is 3a1b2c4d: 8 characters for 10 letters, so it is shorter.

    what it remembers to know where it is
    run's letter
    not yet
    run so far
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

the steps, in plain words
  1. the first letter starts a run of 1Python lines 10 and 11
  2. for each next letter, hold it against the run's letterPython lines 12 and 13
  3. the same: the run grows by 1Python line 14
  4. different: write the run's length and letter, and start a run of the new letterPython lines 16, 17 and 18
  5. at the end, write the last run; what is written is the codePython lines 19 and 20
the same in Python

The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.

def run_length_encoding(text):
    """A text of small letters written as its runs, each as its length and letter.

    Read from the left, each next letter is held against the run's letter. The
    same, and the run grows; different, and the run is written and the letter
    starts a new one. At the end the last run is written. Returns the code, so
    aaab gives 3a1b.
    """
    code = ""  # nothing written yet
    letter = text[0]  # the first letter starts a run
    length = 1  # of 1
    for next_letter in text[1:]:  # each next letter
        if next_letter == letter:  # held against the run's letter
            length += 1  # the same: the run grows by 1
        else:
            code += str(length) + letter  # different: write the run
            letter = next_letter  # and start a run of the new letter
            length = 1
    code += str(length) + letter  # at the end, write the last run
    return code  # the code

how it scales

The plot counts the comparisons the method makes on a text of nn letters, measured from 10 letters to 100,000.

Each dotted line up is ten times the one below, and each line across is ten times the one before. A count that grows in step with nn climbs one line up for each line across. The comparisons do: 9 at 10 letters, 99,999 at 100,000. Question 1 in section 4 works out why.

letters compared, ten times more at each mark up

slope 1102104106101102103104105106107slope 1101102103104105106107101102103104105106107slope 1101102103104105106107101102103104105106107

nn, how many letters the text has, ten times more at each mark to the right

  • any text of nn letters, as every text of that length makes the same comparisons; one with no letter twice in a row, such as xyzx, writes the mostsolid where measured by running it; dashed where its formula carries it on to ten millionslope 1: ten times n, 10 times the work
how long these comparisons take, at a billion a second
nnletters comparedtime
1,000999about 999 nanoseconds
100,00099,999about 100 microseconds
10,000,0009,999,999about 10 milliseconds

The letters compared are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.

make these counts yourself

Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.

"""Count run-length encoding's comparisons yourself, as the plot on this page does.

Run it with Python 3.12 or later. For each n it prints the comparisons the
method makes on a text of n letters, x, y and z in turn, and the characters
its code has, up to n = 100,000. The counts are the same on any computer; only
the time differs.
"""


def run_length_encoding(text):
    """A text of small letters written as its runs, each as its length and letter.

    Read from the left, each next letter is held against the run's letter. The
    same, and the run grows; different, and the run is written and the letter
    starts a new one. At the end the last run is written. Returns the code, so
    aaab gives 3a1b.
    """
    code = ""  # nothing written yet
    letter = text[0]  # the first letter starts a run
    length = 1  # of 1
    for next_letter in text[1:]:  # each next letter
        if next_letter == letter:  # held against the run's letter
            length += 1  # the same: the run grows by 1
        else:
            code += str(length) + letter  # different: write the run
            letter = next_letter  # and start a run of the new letter
            length = 1
    code += str(length) + letter  # at the end, write the last run
    return code  # the code


def count(text):
    """The same method on text, counting each comparison it makes."""
    comparisons = 0
    letter = text[0]
    for next_letter in text[1:]:
        comparisons += 1  # held against the run's letter
        if next_letter != letter:
            letter = next_letter  # a new run starts
    return comparisons


if __name__ == "__main__":
    print(f"{'n':>7} {'comparisons':>12} {'characters':>11}")
    for n in (10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10_000, 20_000, 50_000, 100_000):
        text = ("xyz" * (n // 3 + 1))[:n]
        print(f"{n:>7} {count(text):>12} {len(run_length_encoding(text)):>11}")

best, worst and average

Best, worst and average usually name different inputs of one size. Here every text of nn letters makes the same comparisons, whatever its letters. So the table has one column, under the name worst. Its characters written are the most any text of nn letters writes: a text with no letter twice in a row, as question 2 shows.

A case is one kind of input. A bound says how fast its cost grows as nn grows.

The count is in the grid. Here it is n−1n - 1, which stays between half of nn and nn from 2 up, so every bound is of nn: O(n)O(n), Ω(n)\Omega(n) and Θ(n)\Theta(n). Section 4 shows it.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
worstany text of nn letters, as every text of that length makes the same comparisons; one with no letter twice in a row, such as xyzx, writes the most
letters comparedn−1n - 1
characters writtenat most 2n2n; exactly 2n2n with no letter twice in a row
how the letters compared grow in each case
tight, Θ\ThetaΘ(n)\Theta(n)
ceiling, OOO(n)O(n)
floor, Ω\OmegaΩ(n)\Omega(n)

extra memory: the run's letter and its length so far, and the code, at most 2n2n characters

Extra memory is the room it needs on top of the input itself, while it runs.

textletterscomparisonscharacters written
aa212
ab214
aaabccdddd1098
xyzxyzxyzx10920
zzzzzzzzzz1093
Counted by running the method. The comparisons follow the letters alone. The characters written follow the runs.

where the formula comes from

Two questions, each worked line by line. Question 1 is the count the plot draws.

Question 1: how many comparisons, CC, does the method make on a text of nn letters?
  1. the move: one comparison each, after the first

    the line:
    C=n−1C = n - 1
    letterheld againstsamecomparisons so far
    a--0
    aayes1
    bano2
    cbno3
    ccyes4
    ccyes5
    aabccc: the first a starts a run. Each of the other 5 letters is compared once, the same or not.

    why it is allowed: The first letter starts a run, with nothing to compare. Each other letter is held against the run's letter once, and the method never goes back. For aabccc, 5.

  2. the move: a ceiling

    the line:
    C≤nC \le n

    why it is allowed: By line 1, as n−1n - 1 is less than nn.

  3. the move: read the bound

    the line:
    C∈O(n)C \in O(n)

    why it is allowed: By line 2, with the fixed multiple 1, from 1 letter on.

  4. the move: a floor

    the line:
    C≥n2C \ge \frac{n}{2}
    half of nn - 1n
    112
    234
    356
    5910
    From 2 letters up, n−1n - 1 is at least half of nn, and below nn.

    why it is allowed: By line 1. From 2 letters up, 1 is at most half of nn, so n−1n - 1 is at least nn less half of nn, which is half of nn. For 6, 5 is at least 3.

  5. the move: read the bound

    the line:
    C∈Ω(n)C \in \Omega(n)

    why it is allowed: By line 4, with the fixed multiple a half, from 2 letters on.

  6. the move: both together

    the line:
    C∈Θ(n)C \in \Theta(n)

    why it is allowed: Lines 3 and 5 bound CC by the same growth.

try it with a small nn: at n=6n = 6, line 1 gives C=5C = 5, which you can work out by hand

Question 2: how many characters, WW, does the method write for a text of nn letters with no letter twice in a row? And why does no text of nn letters write more?
  1. the move: every run is one letter

    the line:
    no letter twice in a row:n runs of 1 letter\begin{gathered} \text{no letter twice in a row:} \\ n \text{ runs of 1 letter} \end{gathered}

    why it is allowed: The first letter starts a run. Each other letter differs from the one before, so it starts a new run, ended by the next letter or the end. xyzx has 4 runs.

  2. the move: count them

    the line:
    W=2nW = 2n

    why it is allowed: By line 1, nn runs, and each writes 1, then its letter, 2 characters. For xyzx, 1x1y1z1x, 8.

  3. the move: a longer run

    the line:
    a run of L letters writesthe digits of L, then 1 letter\begin{gathered} \text{a run of } L \text{ letters writes} \\ \text{the digits of } L\text{, then 1 letter} \end{gathered}
    runLwritescharacters
    b11b2
    aaa33a2
    zzzzzzzzzz1010z3
    A run of 1 writes twice its letters. Longer runs write fewer.

    why it is allowed: The method writes each run as its length, then its letter. aaa writes 3a, 2 characters; ten z's write 10z, 3, as 10 has two digits.

  4. the move: put the digits' limit into line 3

    the line:
    from L of 2 up, a run writesat most L characters\begin{gathered} \text{from } L \text{ of 2 up, a run writes} \\ \text{at most } L \text{ characters} \end{gathered}
    Ldigitscharacterstwice L
    2124
    91218
    102320
    10034200
    From 2 letters up, a run writes at most its letters, and far under twice them.

    why it is allowed: 2 to 9 have 1 digit, and 1 is at most LL less 1. 10 to 99 have 2 digits and are at least 10; 100 to 999 have 3 and are at least 100. Each extra digit makes the smallest LL 10 times bigger but adds only 1 digit. So from 2 up, the number LL has at most LL less 1 digits; line 3 adds 1 letter, so at most LL.

  5. the move: each run at most twice its letters

    the line:
    a run of L letters writesat most 2L\begin{gathered} \text{a run of } L \text{ letters writes} \\ \text{at most } 2L \end{gathered}
    runLwritestwice L
    aa224
    b122
    ccc326
    total6612
    aabccc, each run writes at most twice its letters, so the code, 6 characters, is at most twice the text, 12.

    why it is allowed: A run of 1 writes 2 by line 3. From 2 up, at most LL by line 4, under 2L2L.

  6. the move: add up the runs

    the line:
    any text of n letterswrites at most 2n\begin{gathered} \text{any text of } n \text{ letters} \\ \text{writes at most } 2n \end{gathered}

    why it is allowed: By line 5, and the runs' letters add up to nn, so the code has at most 2n2n characters. Exactly 2n2n only when every run is 1 letter, as by line 5 a longer run writes at most LL, under 2L2L.

try it with a small nn: at n=4n = 4, line 2 gives W=8W = 8, which you can work out by hand

count it yourself

aabccc, step by step.

aabccc, every step written down
stepwhat happensletters comparedcharacters written
1The first letter, a, starts a run of 1.00
2The next letter is a too, so the run grows to 2.10
3The next letter, b, is not a. Write the run under its first letter: 2, then a. Then b starts a run of 1.22
4The next letter, c, is not b. Write the run under its first letter: 1, then b. Then c starts a run of 1.34
5The next letter is c too, so the run grows to 2.44
6The next letter is c too, so the run grows to 3.54
7Done: write the last run, 3, then c. The code is 2a1b3c: 6 characters for 6 letters, the same length.56

In all, 5 letters compared. The formula from section 4, n−1n - 1, gives C=5C = 5 at n=6n = 6: the same.

where you meet it

Wherever long runs are common, as in drawings with large plain areas, a form of this method is used.

  • fax machines

    A fax sends a page line by line. Each line is runs of white dots and black dots taking turns, white first, so it sends only the runs' lengths. Each length up to 63 has its own code; a longer one sends a code for its multiple of 64 first. Some codes are much shorter than others.

    source: ITU-T Recommendation T.4, Standardization of Group 3 facsimile terminals for document transmission (opens in a new tab)

  • Windows bitmap files

    A bitmap file may store its dots with RLE8. Two bytes, a count from 1 to 255 and a colour's number, stand for that many dots of that colour; a byte is a stored number from 0 to 255.

    source: Microsoft's documentation, Bitmap Compression (opens in a new tab)

  • TIFF's PackBits

    TIFF image files can use PackBits. A run of 2 to 128 equal bytes can be stored as 2 bytes: how many, then the byte. Bytes with no repeats are stored as they are, after one byte saying how many, up to 128 at a time.

    source: Aldus Corporation's TIFF Revision 6.0 specification (opens in a new tab) (1992, now Adobe's), section 9, PackBits Compression

dotslengths sent
white 5, black 3, white 85, 3, 8
black 2, white 140, 2, 14
Two short lines of 16 dots, sent as a fax sends its real lines of 1,728 dots. A line starting black sends a white run of 0 first.

what is used instead

In ordinary words a run is seldom longer than 2. So files of words use other methods: Huffman coding, which gives common letters short codes, or a method that finds whole stretches seen before. The books warn that data already compressed, such as a JPEG photograph, only grows when compressed again (volume three, chapter 36).

how it compares

Three ways to write a text. The two that write runs each make n−1n - 1 comparisons; keeping the text as it is makes none. They differ in what they write.

wayaaabccddddxyzxyzxyzxzzzzzzzzzz
the text as it is101010
every run as length and letter8203
a run of 1 as its letter alone7103
Characters written for three texts of 10 letters. A run of 1 written as its letter alone costs 1, and a longer run at most its letters (question 2, line 4), so no text grows. PackBits, in section 6, nearly manages this: 128 bytes with no repeats become 129.