# The Expander

> What goes in small comes out big.

Canonical URL: <https://datadriven.io/problems/the_expander>

Domain: Python · Difficulty: easy · Seniority: L4

## 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.

## 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**

```python
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
```

> **Time and Space Complexity**
>
> **Time:** O(n + m) where n is the encoded length and m is the decoded output length.
> 
> **Space:** O(m) for the result string.

> **Interviewers Watch For**
>
> Correct handling of multi-digit counts. `12a` means 12 repetitions of `a`, not `1` followed by `2a`.

> **Common Pitfall**
>
> Not resetting the digit buffer after each character. This corrupts subsequent run counts.

---

## Common follow-up questions

- What if count is 0? _(Tests that 0 repetitions means the character is omitted.)_
- How would you encode a string into this format? _(Tests tracking consecutive runs and writing count+char.)_
- What if the input has no digits (all counts are 1)? _(Tests adding a default count when no digits precede a character.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/the_expander)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.