Neural Mastery
← Practice
Run-Length String Compressioneasy

Run-Length String Compression

easy Python for AI 10–15 min

NumPy allowed · plain Python earns 10 bonus points

Encode repeated consecutive characters into character-count pairs, the cornerstone of lossless text and bitmap data compression.

Related Skills

Task

Implement run_length_encode(text): walk through the string and replace each run of identical consecutive characters with the character followed by the count of repetitions. Return "" for an empty string.

Function Signature

run_length_encode(text: str) -> str

Examples

Example 1: Repeated Runs
Input: text = 'AAABBBCC'
Output: 'A3B3C2'
Example 2: No Consecutive Repeats
Input: text = 'ABCD'
Output: 'A1B1C1D1'
Example 3: Empty String
Input: text = ''
Output: ''

Constraints

  • Libraries are allowed; a plain-Python solution earns 10 bonus points.
  • Text consists of printable ASCII characters.
  • Runs must preserve the exact order of appearance.
Python3Saved ✓
def run_length_encode(text: str) -> str:
"""Compress consecutive identical characters in text using run-length encoding.
For example, 'AAABBC' becomes 'A3B2C1'. Empty string returns empty string."""
# Your implementation here
pass

Case 1: Repeated Runs
Input: text = 'AAABBBCC'
Expected: 'A3B3C2'
Case 2: No Consecutive Repeats
Input: text = 'ABCD'
Expected: 'A1B1C1D1'
Case 3: Empty String
Input: text = ''
Expected: ''