Skip to the content

Compress the text

Problem

An old and simple way to compress: swap every run of repeated characters for how many there are and the character. That way "AABBBCCCC" is stored as "2A3B4C".

Write a function that takes a text and returns that compressed version. The rules: only characters repeated in a row count, so "AABAA" gives "2AB2A". A character on its own goes without a number: "XYZ" stays the same. Uppercase and lowercase are different, and spaces get compressed too. With an empty text you return an empty text.

Examples

  • An empty text

    "" → ""

  • Nothing repeated

    "XYZ" → "XYZ"

  • All repeated

    "AABBBCCCC" → "2A3B4C"

  • Lowercase

    "aabbbcccc" → "2a3b4c"

  • Only the ones in a row

    "AABAA" → "2AB2A"

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def compress_text(text):
    pass

JavaScript

function compressText(text) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n) challenges

See all challenges →