L2 · Working engineerStrings~8 min · 5 tests#26

String Compression (Run-Length Encoding)

Compress consecutive repeated characters as char+count, like 'aaabbcccc' → 'a3b2c4', in one O(n) pass. Practise run-length encoding in Python.

The problem

Compress s by replacing each run of the same character with the character followed by the run length.

"aaabbcccc" → "a3b2c4". Every run gets a count, even a run of 1 ("abc" → "a1b1c1"). Empty input gives "".

Examples

  1. Example 1

    Input

    compress('aaabbcccc')

    Expected output

    'a3b2c4'
  2. Example 2

    Input

    compress('abc')

    Expected output

    'a1b1c1'

+ 3 hidden tests on Submit — same char in two separate runs.

Edge cases to ask about

  • Empty string
  • Single character
  • Same character in separate runs
  • Run of 10+ (two-digit count)

Hints

0/3

    How an interviewer scores this

    0/9
    Python 3.13 · compress
    ⌘/Ctrl + Enter runs the examples

    Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.

    Complexity Lab

    What does this cost as n grows?

    Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and measure your code against the optimal one at growing input sizes.

    Time complexity of the optimal solution
    Space complexity (extra memory)

    Pick both to reveal the answer.

    Measure it

    Runs the function on inputs of size 250 up to 16,000 and records the time and peak memory. Slow solutions stop early — a short curve is itself the answer.

    From brute force to optimal

    The progression an interviewer wants to hear, one step at a time.

    ApproachTimeSpaceIdea
    String += in a loopO(n) amortised in CPythonO(n)Works, but relies on an implementation detail.
    List of parts + joinO(n)O(n)One pass, flush each run when the character changes.
    bestitertools.groupbyO(n)O(n)''.join(f'{k}{len(list(g))}' for k, g in groupby(s)).
    Walkthrough of the optimal approach (try it yourself first)

    Walk the string keeping run_char and run_len. When the character changes, append f"{run_char}{run_len}" to a list and start a new run. After the loop, flush the last run — the most commonly forgotten line.

    itertools.groupby groups consecutive equal items and makes this a one-liner.

    Complexity: O(n) time, O(n) space. Single pass; the output can be up to 2n characters long.

    Reveal the reference solution
    def compress(s):
        if not s:
            return ""
        parts = []
        run_char, run_len = s[0], 1
        for ch in s[1:]:
            if ch == run_char:
                run_len += 1
            else:
                parts.append(f"{run_char}{run_len}")
                run_char, run_len = ch, 1
        parts.append(f"{run_char}{run_len}")
        return "".join(parts)

    Follow-ups interviewers ask

    • Return the original if the compressed form is not shorter.
    • Write the decoder.

    Frequently asked interview questions

    Core interview concepts, complexities, and follow-ups scored by hiring teams.

    What is the time complexity of String Compression (Run-Length Encoding) in Python?

    The optimal solution runs in O(n) time and O(n) auxiliary space. Single pass; the output can be up to 2n characters long.

    What is the brute-force approach, and how do you optimise it?

    String += in a loop: O(n) amortised in CPython time, O(n) space. Works, but relies on an implementation detail. List of parts + join: O(n) time, O(n) space. One pass, flush each run when the character changes. itertools.groupby: O(n) time, O(n) space. ''.join(f'{k}{len(list(g))}' for k, g in groupby(s)).

    What follow-up questions do interviewers ask about String Compression (Run-Length Encoding)?

    Return the original if the compressed form is not shorter. Write the decoder.