Compact a run-length encoded event log

Python data engineering interview problem. Difficulty: beginner. Pattern: Strings. About 10 minutes. Free to practice.

A verbose event log repeats the same character (or code) many times in a row. Compaction stores run-length pairs to save space.

To save space, a log stores repeated characters as the character plus the number of times it repeats. This is called run-length encoding. Compress a string by replacing each run of the same character with the character and the length of the run. An empty string stays empty. Write rle_compress(s). 'aaabbc' becomes 'a3b2c1'. An empty string gives ''. The starter file already has the function name and its print lines. Keep them and fill in the body.

Requirements

  • Replace each run with the character and its count.
  • Single characters get a count of 1.
  • Keep the order of the runs.
  • An empty string returns ''.

Constraints

  • s is a string, usually letters.
  • Counts are written as plain digits.

Examples

Input: rle_compress('aaabbc') Output: 'a3b2c1' This input follows the stated rules and produces this output.

Topics: lakebench, python, strings.

More Python interview questions · All interview problems · Learn data engineering

beginner

Compact a run-length encoded event log

Interview-style drill: Compress a sequence of repeated status codes into a run-length encoded form.

Compact a run-length encoded event log (compress consecutive repeats).