Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Compress repeated characters using counts

Implement run-length encoding by collapsing consecutive repeated characters into character+count pairs.

Python practice22 minString PatternsAdvancedLast updated March 18, 2026

Problem statement

Given a string s, return a compressed version using run-length encoding: each consecutive group of the same character is replaced by the character followed by the number of times it appears consecutively. The function should be case-sensitive and preserve non-letter characters. If the input is empty, return an empty string.

Task

Write a function that compresses a string by replacing runs of identical characters with the character followed by the count of repetitions (always include the count, even when it is 1).

Examples

Basic compression

Input

aaabbc

Output

a3b2c1

Three 'a's become 'a3', two 'b's become 'b2', one 'c' becomes 'c1'.

Input format

A single string s.

Output format

A single string representing the run-length encoded form of s.

Constraints

0 <= len(s) <= 10^6. Characters may include letters, digits, punctuation, and whitespace. Must be O(n) time and O(1) additional space (excluding output).

Samples

Sample 1

Input

WWWWaa!!

Output

W4a2!2

Four 'W's, two 'a's, two '!' characters.