Easy: Warm-Ups · Problem 6 of 82

Run-Length Encoding

EasyStringsPython

A run is a group of the same character in a row. Write run_length(text) that replaces every run with the character followed by the length of the run.

"aaabcc" becomes "a3b1c2". A run of length one still gets its count. The empty string gives the empty string.

Understand the problem

Apply the rule by hand.

What is run_length("aabaa")?

The runs are aa, b, aa. The two separate runs of a are not combined, because they are not next to each other. So the result is a2b1a2.

What is run_length("z")?

A run of one character still gets its count: z1.

Write the solution

Return the encoded string.

def run_length(text):
    # Write your code here.
    pass
Hint 1: a question to ask yourself

While walking along the text, what do you need to remember about the run you are in? And when do you know a run has ended?

Hint 2: the shape of the answer

Keep the current character and its count. When the next character is different, write the pair and start a new run. Do not forget to write the last run after the loop.

Reflect

Solution

def run_length(text):
    if not text:
        return ""
    parts = []
    current, count = text[0], 1
    for ch in text[1:]:
        if ch == current:
            count += 1
        else:
            parts.append(f"{current}{count}")
            current, count = ch, 1
    parts.append(f"{current}{count}")
    return "".join(parts)

Another way: itertools.groupby

from itertools import groupby

def run_length(text):
    return "".join(f"{ch}{len(list(group))}" for ch, group in groupby(text))

What this tests: iterating with state, the "last group" edge case, f-strings, and knowing itertools.groupby.

The classic bug: the loop writes a run only when it sees a different character, so the last run is never written unless you add it after the loop. Test with a string whose last run is long.

groupby groups neighbours only, exactly what a run is. (It is different from a dictionary of counts, which would merge the two aa runs in aabaa.)

Cost: O(n) time, O(n) space for the result.

What an interviewer might ask next: Now write the decoder: "a3b1c2" back to "aaabcc". What goes wrong if a count has two digits, such as a12? (Parse digits until the next letter.)