The Expander

An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
easy
Seniority
L4
Asked in
Ripple

Problem

Given an RLE-encoded string where each run is count followed by char (e.g. '3a2b1c'), return the decoded string. Counts are positive integers; characters are single letters.

What goes in small comes out big.

Example 1

Input:

encoded = "3a2b1c"

Output:

"aaabbc"

Example 2

Input:

encoded = "1x4y"

Output:

"xyyyy"

Worked solution and explanation

Why this problem exists in real interviews

This tests run-length decoding, the inverse of encoding. It probes string parsing with digit accumulation and character repetition, a pattern common in compression and serialization pipelines.


Break down the requirements

Step 1: Accumulate digit characters into a count

Consecutive digits form a multi-digit number.

Step 2: When a letter is encountered, repeat it count times

Convert the accumulated digits to an integer and repeat the character.

Step 3: Reset and continue

Clear the digit buffer and process the next run.


The solution

Digit accumulation and character expansion
def decode(encoded: str) -> str:
    result = ""
    num_buffer = ""
    for ch in encoded:
        if ch.isdigit():
            num_buffer += ch
        else:
            count = int(num_buffer)
            for _ in range(count):
                result += ch
            num_buffer = ""
    return result

Common follow-up questions