Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Run-Length Encoding Implementation in Python

11 min readbeginner
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓Run-Length Encoding runs in O(n) time and O(n) space, in Python as in every other language.
  • ✓itertools.groupby (from itertools import groupby) is the RLE primitive: called with no key it yields (value, group_iterator) for every maximal run of adjacent equal items, which is precisely a run.
  • ✓Reviewers want groupby rather than a hand-rolled index loop, and ''.join(parts) rather than out += part.
  • ✓The Python trap: groupby's group iterator is a view over the SAME underlying iterator, not a copy. The instant you advance to the next (key, group) pair, the previous group is silently exhausted.
  • ✓CPython's groupby is C code, so it beats an equivalent Python-level loop by a large constant even though both are O(n).

What Run-Length Encoding actually is

Run-length encoding replaces each maximal run of identical adjacent symbols with the symbol plus its repeat count: aaabbc becomes a3b2c. One left-to-right pass with a single symbol of lookahead, no dictionary, no sliding window, no back-references. Engineers reach for it where the data is already run-heavy: 1-bit fax and bitmap scanlines, PCX/BMP/TGA sprite masks, sparse column masks, and as the cheap final stage after a transform that manufactures runs, such as move-to-front output after Burrows-Wheeler. On random text it inflates, so the format almost always needs an escape or a literal-block mode.

Run-Length Encoding in Python: what you actually reach for

itertools.groupby (from itertools import groupby) is the RLE primitive: called with no key it yields (value, group_iterator) for every maximal run of adjacent equal items, which is precisely a run. Accumulate into a list and finish with str.join. For binary payloads groupby still works because bytes iterates as int, and memoryview avoids the slice copies. The regex route is re.finditer(r'(.)\1*', s, re.S): each match is one whole run, and re.DOTALL is mandatory or a run of newlines is skipped entirely.

Python implementation

Reviewers want groupby rather than a hand-rolled index loop, and ''.join(parts) rather than out += part. They reject ch.isdigit() in the decoder: it is True for '٣' (Arabic-Indic three), which int() happily parses as 3, so the decoder silently accepts a count your encoder can never emit; and it is True for '²' and '³', which int() rejects outright, so the same decoder crashes with ValueError on input it just declared to be a digit. Use ch in '0123456789', or ch.isascii() and ch.isdigit(). Annotate str -> str and return a str, not a list of tuples, unless the caller asked for runs.
python
from itertools import groupby

def encode(s: str) -> str:
    parts = []
    for ch, grp in groupby(s):
        n = sum(1 for _ in grp)        # consume grp NOW, not later
        parts.append(ch if n == 1 else f"{ch}{n}")
    return "".join(parts)

DIGITS = "0123456789"                  # str.isdigit() also accepts '²' and '٣'

def decode(s: str) -> str:
    parts, i, end = [], 0, len(s)
    while i < end:
        ch = s[i]
        i += 1
        j = i
        while j < end and s[j] in DIGITS:
            j += 1
        parts.append(ch * (int(s[i:j]) if j > i else 1))
        i = j
    return "".join(parts)

assert encode("aaabbc") == "a3b2c"
assert decode(encode("aaabbc")) == "aaabbc"
assert [k for k, _ in groupby("aab")] == ["a", "b"]

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The Python-specific trap

groupby's group iterator is a view over the SAME underlying iterator, not a copy. The instant you advance to the next (key, group) pair, the previous group is silently exhausted. So list(groupby(s)) hands you keys attached to empty groups, and [(k, len(list(g))) for k, g in groupby(s)] only works because the comprehension consumes g before stepping. Reorder it, stash the groups in a dict, or sort by count first, and every count becomes 0. No exception, no warning: you get a0b0c0 and a green test on the empty-string case.

Performance in Python, beyond the O(n)

CPython's groupby is C code, so it beats an equivalent Python-level loop by a large constant even though both are O(n). ''.join(parts) sums the lengths and allocates once. out += ch looks fine because CPython special-cases an in-place resize when the string's refcount is 1, but that is a CPython implementation detail: it vanishes under PyPy, and the moment anything else holds a reference you are back to quadratic copying. Memory: an all-ASCII str is stored at one byte per character, and a single astral character promotes the whole object to four. The asymptotic cost is the same in every language, O(n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Run-Length Encoding between languages.

Real-World Applications

Run-Length Encoding is used extensively in production software: database engines, compilers, operating systems, and application frameworks all use Run-Length Encoding internally. In Python specifically, libraries like NumPy, Django, and Flask use similar patterns. Understanding Run-Length Encoding helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Run-Length Encoding appears frequently in phone screens and early-round coding interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Run-Length Encoding over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Run-Length Encoding to build pattern recognition. In Python, demonstrate proficiency with list comprehensions and generator expressions to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Python code that is both correct and maintainable.

Frequently Asked Questions

Which Python type or library should I use for Run-Length Encoding?

itertools.groupby (from itertools import groupby) is the RLE primitive: called with no key it yields (value, group_iterator) for every maximal run of adjacent equal items, which is precisely a run. Accumulate into a list and finish with str.join. For binary payloads groupby still works because bytes iterates as int, and memoryview avoids the slice copies. The regex route is re.finditer(r'(.)\1*', s, re.S): each match is one whole run, and re.DOTALL is mandatory or a run of newlines is skipped entirely.

What is the most common Python mistake when implementing Run-Length Encoding?

groupby's group iterator is a view over the SAME underlying iterator, not a copy. The instant you advance to the next (key, group) pair, the previous group is silently exhausted. So list(groupby(s)) hands you keys attached to empty groups, and [(k, len(list(g))) for k, g in groupby(s)] only works because the comprehension consumes g before stepping. Reorder it, stash the groups in a dict, or sort by count first, and every count becomes 0. No exception, no warning: you get a0b0c0 and a green test on the empty-string case.

How does Run-Length Encoding actually perform in Python?

CPython's groupby is C code, so it beats an equivalent Python-level loop by a large constant even though both are O(n). ''.join(parts) sums the lengths and allocates once. out += ch looks fine because CPython special-cases an in-place resize when the string's refcount is 1, but that is a CPython implementation detail: it vanishes under PyPy, and the moment anything else holds a reference you are back to quadratic copying. Memory: an all-ASCII str is stored at one byte per character, and a single astral character promotes the whole object to four. Time complexity is O(n) and space is O(n).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Related Articles

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

If you are a student, see what Devin offers students for free on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Want 50 audits a day? Explore SeekerPro

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.